<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>项目详情 - 学术研究自动化系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            line-height: 1.6;
            color: #333;
            background: #f5f7fa;
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 2rem 0;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 2rem;
        }
        
        .project-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 1rem;
        }
        
        .project-title {
            font-size: 2rem;
            margin-bottom: 0.5rem;
        }
        
        .project-meta {
            display: flex;
            gap: 2rem;
            font-size: 0.9rem;
            opacity: 0.9;
        }
        
        .project-status {
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: bold;
            text-transform: uppercase;
            background: rgba(255,255,255,0.2);
        }
        
        .main-content {
            display: grid;
            grid-template-columns: 2fr 1fr;
            gap: 2rem;
            margin-top: 2rem;
            position: relative;
        }
        
        /* 智能助手聊天窗口 */
        .ai-assistant {
            position: fixed;
            bottom: 20px;
            right: 20px;
            width: 400px;
            height: 500px;
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            display: flex;
            flex-direction: column;
            z-index: 1000;
            transform: translateY(100%);
            transition: transform 0.3s ease;
        }
        
        .ai-assistant.active {
            transform: translateY(0);
        }
        
        .ai-assistant-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 1rem;
            border-radius: 15px 15px 0 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .ai-assistant-title {
            font-weight: bold;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .ai-assistant-close {
            background: none;
            border: none;
            color: white;
            font-size: 1.2rem;
            cursor: pointer;
            padding: 0.25rem;
            border-radius: 3px;
        }
        
        .ai-assistant-close:hover {
            background: rgba(255,255,255,0.2);
        }
        
        .ai-chat-messages {
            flex: 1;
            padding: 1rem;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
            gap: 1rem;
        }
        
        .ai-message {
            display: flex;
            gap: 0.5rem;
            animation: fadeInUp 0.3s ease;
        }
        
        .ai-message.user {
            flex-direction: row-reverse;
        }
        
        .ai-message-avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1rem;
            flex-shrink: 0;
        }
        
        .ai-message.ai .ai-message-avatar {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .ai-message.user .ai-message-avatar {
            background: #e9ecef;
            color: #495057;
        }
        
        .ai-message-content {
            background: #f8f9fa;
            padding: 0.75rem 1rem;
            border-radius: 15px;
            max-width: 80%;
            word-wrap: break-word;
        }
        
        .ai-message.ai .ai-message-content {
            background: #e3f2fd;
            border-bottom-left-radius: 5px;
        }
        
        .ai-message.user .ai-message-content {
            background: #667eea;
            color: white;
            border-bottom-right-radius: 5px;
        }
        
        .ai-progress-container {
            padding: 0 1rem;
            margin-bottom: 1rem;
        }
        
        .ai-progress-bar {
            width: 100%;
            height: 8px;
            background: #e9ecef;
            border-radius: 4px;
            overflow: hidden;
            margin-bottom: 0.5rem;
        }
        
        .ai-progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #667eea, #764ba2);
            border-radius: 4px;
            transition: width 0.3s ease;
            width: 0%;
        }
        
        .ai-progress-text {
            font-size: 0.8rem;
            color: #666;
            text-align: center;
        }
        
        .ai-input-container {
            padding: 1rem;
            border-top: 1px solid #e9ecef;
            display: flex;
            gap: 0.5rem;
        }
        
        .ai-input {
            flex: 1;
            padding: 0.75rem;
            border: 1px solid #ddd;
            border-radius: 20px;
            outline: none;
            font-size: 0.9rem;
        }
        
        .ai-input:focus {
            border-color: #667eea;
        }
        
        .ai-send-btn {
            background: #667eea;
            color: white;
            border: none;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: background 0.3s;
        }
        
        .ai-send-btn:hover {
            background: #5a6fd8;
        }
        
        .ai-send-btn:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        
        /* 智能助手触发按钮 */
        .ai-trigger-btn {
            position: fixed;
            bottom: 20px;
            right: 20px;
            width: 60px;
            height: 60px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 50%;
            cursor: pointer;
            font-size: 1.5rem;
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
            z-index: 999;
            transition: transform 0.3s ease;
        }
        
        .ai-trigger-btn:hover {
            transform: scale(1.1);
        }
        
        .ai-trigger-btn.hidden {
            display: none;
        }
        
        /* 动画效果 */
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        @keyframes typing {
            0%, 60%, 100% {
                transform: translateY(0);
            }
            30% {
                transform: translateY(-10px);
            }
        }
        
        .typing-indicator {
            display: flex;
            gap: 3px;
            padding: 0.75rem 1rem;
        }
        
        .typing-dot {
            width: 6px;
            height: 6px;
            background: #999;
            border-radius: 50%;
            animation: typing 1.4s infinite;
        }
        
        .typing-dot:nth-child(2) {
            animation-delay: 0.2s;
        }
        
        .typing-dot:nth-child(3) {
            animation-delay: 0.4s;
        }
        
        .content-section {
            background: white;
            border-radius: 10px;
            padding: 2rem;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            margin-bottom: 2rem;
        }
        
        .section-title {
            font-size: 1.3rem;
            margin-bottom: 1.5rem;
            color: #333;
            border-bottom: 2px solid #667eea;
            padding-bottom: 0.5rem;
        }
        
        .tabs {
            display: flex;
            border-bottom: 1px solid #eee;
            margin-bottom: 2rem;
        }
        
        .tab {
            padding: 1rem 2rem;
            cursor: pointer;
            border-bottom: 2px solid transparent;
            transition: all 0.3s ease;
        }
        
        .tab.active {
            border-bottom-color: #667eea;
            color: #667eea;
            font-weight: bold;
        }
        
        .automation-step {
            display: flex;
            align-items: center;
            padding: 0.5rem 0;
            border-bottom: 1px solid #e0e0e0;
        }
        
        .automation-step:last-child {
            border-bottom: none;
        }
        
        .step-icon {
            width: 30px;
            text-align: center;
            margin-right: 1rem;
            font-size: 1.2rem;
        }
        
        .step-text {
            flex: 1;
            font-weight: 500;
        }
        
        .step-status {
            font-size: 0.9rem;
            padding: 2px 8px;
            border-radius: 12px;
            background: #f5f5f5;
            color: #666;
        }
        
        .automation-step.running .step-icon {
            animation: spin 1s linear infinite;
        }
        
        .automation-step.running .step-status {
            background: #fff3cd;
            color: #856404;
        }
        
        .automation-step.completed .step-status {
            background: #d4edda;
            color: #155724;
        }
        
        .automation-step.error .step-status {
            background: #f8d7da;
            color: #721c24;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .tab-content {
            display: none;
        }
        
        .tab-content.active {
            display: block;
        }
        
        .btn {
            padding: 10px 20px;
            background: #667eea;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
            transition: background 0.3s ease;
            margin-right: 1rem;
            margin-bottom: 1rem;
        }
        
        .btn:hover {
            background: #5a6fd8;
        }
        
        .btn-success {
            background: #28a745;
        }
        
        .btn-success:hover {
            background: #218838;
        }
        
        .btn-warning {
            background: #ffc107;
            color: #333;
        }
        
        .btn-warning:hover {
            background: #e0a800;
        }
        
        .progress-section {
            margin-bottom: 2rem;
        }
        
        .progress-bar {
            width: 100%;
            height: 12px;
            background: #e9ecef;
            border-radius: 6px;
            overflow: hidden;
            margin-bottom: 1rem;
        }
        
        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #667eea, #764ba2);
            transition: width 0.3s ease;
        }
        
        .phase-list {
            list-style: none;
        }
        
        .phase-item {
            display: flex;
            align-items: center;
            padding: 1rem;
            margin-bottom: 1rem;
            background: #f8f9fa;
            border-radius: 8px;
            border-left: 4px solid #ddd;
        }
        
        .phase-item.completed {
            border-left-color: #28a745;
            background: #d4edda;
        }
        
        .phase-item.in-progress {
            border-left-color: #ffc107;
            background: #fff3cd;
        }
        
        .phase-item.pending {
            border-left-color: #6c757d;
            background: #f8f9fa;
        }
        
        .phase-icon {
            font-size: 1.5rem;
            margin-right: 1rem;
        }
        
        .phase-content {
            flex: 1;
        }
        
        .phase-name {
            font-weight: bold;
            margin-bottom: 0.5rem;
        }
        
        .phase-progress {
            font-size: 0.9rem;
            color: #666;
        }
        
        .literature-item {
            padding: 1rem;
            border: 1px solid #eee;
            border-radius: 8px;
            margin-bottom: 1rem;
        }
        
        .literature-title {
            font-weight: bold;
            color: #333;
            margin-bottom: 0.5rem;
        }
        
        .literature-authors {
            color: #666;
            font-size: 0.9rem;
            margin-bottom: 0.5rem;
        }
        
        .literature-journal {
            color: #667eea;
            font-size: 0.9rem;
            margin-bottom: 0.5rem;
        }
        
        .literature-scores {
            display: flex;
            gap: 1rem;
            font-size: 0.8rem;
        }
        
        .score-badge {
            padding: 2px 8px;
            border-radius: 12px;
            background: #e9ecef;
            color: #495057;
        }
        
        .score-high {
            background: #d4edda;
            color: #155724;
        }
        
        .sidebar {
            display: flex;
            flex-direction: column;
            gap: 2rem;
        }
        
        .quick-actions {
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 1rem;
        }
        
        .stat-item {
            text-align: center;
            padding: 1rem;
            background: #f8f9fa;
            border-radius: 8px;
        }
        
        .stat-number {
            font-size: 2rem;
            font-weight: bold;
            color: #667eea;
        }
        
        .stat-label {
            font-size: 0.9rem;
            color: #666;
        }
        
        .loading {
            text-align: center;
            padding: 2rem;
            color: #666;
        }
        
        .chart-container {
            height: 300px;
            margin: 1rem 0;
            background: #f8f9fa;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #666;
        }
        
        @media (max-width: 768px) {
            .main-content {
                grid-template-columns: 1fr;
            }
            
            .container {
                padding: 0 1rem;
            }
            
            .project-header {
                flex-direction: column;
                gap: 1rem;
            }
            
            .tabs {
                overflow-x: auto;
            }
            
            .ai-assistant {
                width: 100%;
                height: 100%;
                bottom: 0;
                right: 0;
                border-radius: 0;
            }
            
            .ai-assistant-header {
                border-radius: 0;
            }
            
            .ai-trigger-btn {
                bottom: 80px;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="container">
            <div class="project-header">
                <div>
                    <h1 class="project-title" id="projectTitle">加载中...</h1>
                    <div class="project-meta" id="projectMeta">
                        <span>📅 创建时间: --</span>
                        <span>🔬 研究领域: --</span>
                        <span>⏱️ 预期时长: --</span>
                    </div>
                </div>
                <div class="project-status" id="projectStatus">--</div>
            </div>
            <div class="progress-section">
                <div class="progress-bar">
                    <div class="progress-fill" id="progressFill" style="width: 0%"></div>
                </div>
                <p>项目进度: <span id="progressText">0%</span></p>
            </div>
        </div>
    </div>
    
    <div class="container">
        <div style="margin: 2rem 0;">
            <a href="/projects" class="btn">← 返回项目列表</a>
        </div>
        
        <div class="main-content">
            <div class="content-area">
                <div class="content-section">
                    <div class="tabs">
                        <div class="tab active" onclick="switchTab('overview')">项目概览</div>
                        <div class="tab" onclick="switchTab('deliverables')">📦 成果交付</div>
                        <div class="tab" onclick="switchTab('research-plan')">研究计划</div>
                        <div class="tab" onclick="switchTab('literature')">文献研究</div>
                        <div class="tab" onclick="switchTab('experiment')">实验设计</div>
                        <div class="tab" onclick="switchTab('analysis')">数据分析</div>
                    </div>
                    
                    <!-- 项目概览 -->
                    <div id="overview" class="tab-content active">
                        <h2 class="section-title">📋 项目概览</h2>
                        <div id="projectDescription">
                            <div class="loading">正在加载项目信息...</div>
                        </div>
                        
                        <h3 style="margin-top: 2rem; margin-bottom: 1rem;">🎯 研究目标</h3>
                        <ul id="projectObjectives">
                            <li>加载中...</li>
                        </ul>
                        
                        <h3 style="margin-top: 2rem; margin-bottom: 1rem;">📊 项目统计</h3>
                        <div class="stats-grid">
                            <div class="stat-item">
                                <div class="stat-number" id="literatureCount">--</div>
                                <div class="stat-label">文献数量</div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-number" id="reviewedCount">--</div>
                                <div class="stat-label">已审阅</div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-number" id="keyPapersCount">--</div>
                                <div class="stat-label">重点文献</div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-number" id="researchGapsCount">--</div>
                                <div class="stat-label">研究空白</div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 成果交付 -->
                    <div id="deliverables" class="tab-content">
                        <h2 class="section-title">📦 项目成果与交付物</h2>
                        <div style="margin-bottom: 2rem;">
                            <button class="btn btn-success" onclick="loadProjectDeliverables()">🔄 刷新成果数据</button>
                            <button class="btn" onclick="exportDeliverables()">📄 导出成果报告</button>
                        </div>
                        
                        <div id="deliverablesContent">
                            <div style="text-align: center; padding: 3rem; color: #666;">
                                <div style="font-size: 3rem; margin-bottom: 1rem;">📦</div>
                                <h3>项目成果展示</h3>
                                <p style="margin: 1rem 0;">点击"刷新成果数据"查看项目的真实成果和交付物</p>
                                <button class="btn btn-success" onclick="loadProjectDeliverables()">加载成果数据</button>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 研究计划 -->
                    <div id="research-plan" class="tab-content">
                        <h2 class="section-title">📅 研究计划</h2>
                        <div style="margin-bottom: 2rem;">
                            <button class="btn btn-success" onclick="generateResearchPlan()">🤖 智能生成研究计划</button>
                            <button class="btn" onclick="exportResearchPlan()">📄 导出计划</button>
                        </div>
                        
                        <!-- 自动化流程状态指示器 -->
                        <div id="automationStatus" style="display: none; margin-bottom: 2rem; padding: 1rem; background: #e3f2fd; border-radius: 8px; border-left: 4px solid #2196f3;">
                            <h4 style="margin: 0 0 1rem 0; color: #1976d2;">🤖 智能化研究流程</h4>
                            <div id="automationSteps">
                                <div class="automation-step" data-step="plan">
                                    <span class="step-icon">⏳</span>
                                    <span class="step-text">生成研究计划</span>
                                    <span class="step-status">待执行</span>
                                </div>
                                <div class="automation-step" data-step="literature">
                                    <span class="step-icon">⏳</span>
                                    <span class="step-text">智能文献搜索</span>
                                    <span class="step-status">待执行</span>
                                </div>
                                <div class="automation-step" data-step="experiment">
                                    <span class="step-icon">⏳</span>
                                    <span class="step-text">智能实验设计</span>
                                    <span class="step-status">待执行</span>
                                </div>
                                <div class="automation-step" data-step="analysis">
                                    <span class="step-icon">⏳</span>
                                    <span class="step-text">数据分析准备</span>
                                    <span class="step-status">待执行</span>
                                </div>
                            </div>
                        </div>
                        
                        <div id="researchPlanContent">
                            <p style="color: #666; text-align: center; padding: 2rem;">
                                点击"智能生成研究计划"来创建详细的研究计划
                            </p>
                        </div>
                    </div>
                    
                    <!-- 文献研究 -->
                    <div id="literature" class="tab-content">
                        <h2 class="section-title">📚 文献研究</h2>
                        <div style="margin-bottom: 2rem;">
                            <button class="btn btn-success" onclick="searchRealLiterature()">🌐 真实文献搜索</button>
                            <button class="btn" onclick="searchLiterature()">🔍 本地文献搜索</button>
                            <button class="btn" onclick="buildKnowledgeGraph()">🕸️ 构建知识图谱</button>
                            <button class="btn" onclick="generateLiteratureReview()">📝 生成综述</button>
                        </div>
                        
                        <div id="literatureContent">
                            <p style="color: #666; text-align: center; padding: 2rem;">
                                点击"智能文献搜索"开始文献调研
                            </p>
                        </div>
                    </div>
                    
                    <!-- 实验设计 -->
                    <div id="experiment" class="tab-content">
                        <h2 class="section-title">🧪 实验设计</h2>
                        <div style="margin-bottom: 2rem;">
                            <button class="btn btn-success" onclick="generateExperimentDesign()">⚗️ 智能实验设计</button>
                            <button class="btn" onclick="optimizeParameters()">⚙️ 参数优化</button>
                            <button class="btn" onclick="assessFeasibility()">✅ 可行性评估</button>
                        </div>
                        
                        <div id="experimentContent">
                            <p style="color: #666; text-align: center; padding: 2rem;">
                                点击"智能实验设计"来生成实验方案
                            </p>
                        </div>
                    </div>
                    
                    <!-- 数据分析 -->
                    <div id="analysis" class="tab-content">
                        <h2 class="section-title">📊 数据分析</h2>
                        <div style="margin-bottom: 2rem;">
                            <button class="btn btn-success" onclick="analyzeData()">📈 开始数据分析</button>
                            <button class="btn" onclick="generateVisualization()">📊 生成可视化</button>
                            <button class="btn" onclick="extractInsights()">💡 提取洞察</button>
                        </div>
                        
                        <div id="analysisContent">
                            <div class="chart-container">
                                <p>点击"开始数据分析"来分析您的研究数据</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="sidebar">
                <div class="content-section">
                    <h3 class="section-title">🤖 智能研究助手</h3>
                    <div style="background: #f8f9fa; padding: 1rem; border-radius: 8px; margin-bottom: 1rem;">
                        <p style="margin: 0; font-size: 0.9rem; color: #666;">
                            💡 <strong>智能提示:</strong> 生成研究计划后，系统可以自动执行后续的文献搜索、实验设计和数据分析准备工作，让您的研究更加高效！
                        </p>
                    </div>
                    <div class="quick-actions">
                        <button class="btn btn-success" onclick="generateResearchPlan()" style="width: 100%; margin-bottom: 0.5rem;">
                            🤖 智能生成研究计划
                        </button>
                        <button class="btn" onclick="executeFullAutomation()" style="width: 100%; margin-bottom: 0.5rem; background: #28a745; color: white;">
                            🚀 一键执行全流程
                        </button>
                        <hr style="margin: 1rem 0;">
                        <button class="btn" onclick="searchLiterature()" style="width: 100%; margin-bottom: 0.5rem;">搜索文献</button>
                        <button class="btn" onclick="generateExperimentDesign()" style="width: 100%; margin-bottom: 0.5rem;">设计实验</button>
                        <button class="btn" onclick="analyzeData()" style="width: 100%; margin-bottom: 0.5rem;">分析数据</button>
                        <button class="btn btn-warning" onclick="generateReport()" style="width: 100%;">生成报告</button>
                    </div>
                </div>
                
                <div class="content-section">
                    <h3 class="section-title">📈 研究进度</h3>
                    <ul class="phase-list" id="phaseList">
                        <li class="phase-item pending">
                            <div class="phase-icon">⏳</div>
                            <div class="phase-content">
                                <div class="phase-name">加载中...</div>
                                <div class="phase-progress">--</div>
                            </div>
                        </li>
                    </ul>
                </div>
                
                <div class="content-section">
                    <h3 class="section-title">🔍 研究空白</h3>
                    <div id="researchGaps">
                        <p style="color: #666;">暂无数据</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 智能助手触发按钮 -->
    <button class="ai-trigger-btn" id="aiTriggerBtn" onclick="toggleAIAssistant()">
        🤖
    </button>
    
    <!-- 智能助手聊天窗口 -->
    <div class="ai-assistant" id="aiAssistant">
        <div class="ai-assistant-header">
            <div class="ai-assistant-title">
                🤖 智能研究助手
            </div>
            <button class="ai-assistant-close" onclick="toggleAIAssistant()">
                ×
            </button>
        </div>
        
        <div class="ai-chat-messages" id="aiChatMessages">
            <div class="ai-message ai">
                <div class="ai-message-avatar">🤖</div>
                <div class="ai-message-content">
                    您好！我是您的智能研究助手。我可以帮您：<br>
                    • 生成研究计划<br>
                    • 智能搜索文献<br>
                    • 设计实验方案<br>
                    • 准备数据分析<br><br>
                    请告诉我您想要做什么？
                </div>
            </div>
        </div>
        
        <div class="ai-progress-container" id="aiProgressContainer" style="display: none;">
            <div class="ai-progress-bar">
                <div class="ai-progress-fill" id="aiProgressFill"></div>
            </div>
            <div class="ai-progress-text" id="aiProgressText">准备中...</div>
        </div>
        
        <div class="ai-input-container">
            <input type="text" class="ai-input" id="aiInput" placeholder="输入您的问题或指令..." onkeypress="handleAIInputKeyPress(event)">
            <button class="ai-send-btn" id="aiSendBtn" onclick="sendAIMessage()">
                ➤
            </button>
        </div>
    </div>
    
    <script>
        
        // 辅助函数
        function showInfo(message) {
            console.log('ℹ️ ' + message);
            // 这里可以添加UI提示逻辑
        }
        
        function showSuccess(message) {
            console.log('✅ ' + message);
            // 这里可以添加成功提示逻辑
        }
        
        function showError(message) {
            console.error('❌ ' + message);
            // 这里可以添加错误提示逻辑
        }
        
        function showWarning(message) {
            console.warn('⚠️ ' + message);
            // 这里可以添加警告提示逻辑
        }
        
        function showProgress(message, percent) {
            console.log(`🔄 ${message} (${percent}%)`);
            // 这里可以添加进度条逻辑
        }
        
        function hideProgress() {
            console.log('✅ 进度完成');
            // 这里可以添加隐藏进度条逻辑
        }
        
        // 全局变量声明
        const projectId = window.location.pathname.split('/').pop();
        let projectData = null;
        let currentResearchPlan = null;
        let currentWorkflow = null;
        
        // 页面加载时获取项目详情
        document.addEventListener('DOMContentLoaded', function() {
            loadProjectDetail();
        });
        
        // 加载项目详情
        async function loadProjectDetail() {
            try {
                const response = await fetch(`/api/projects/${projectId}`);
                const data = await response.json();
                
                if (data.success) {
                    projectData = data.project;
                    
                    // 如果项目有研究计划，保存到全局变量并渲染
                    if (projectData.research_plan && projectData.research_plan.phases && projectData.research_plan.phases.length > 0) {
                        currentResearchPlan = projectData.research_plan;
                        console.log('✅ 加载已有研究计划，包含', projectData.research_plan.phases.length, '个阶段');
                        
                        // 渲染研究计划到研究计划标签页
                        renderResearchPlan(projectData.research_plan);
                    } else {
                        console.log('ℹ️ 该项目暂无研究计划');
                        // 显示空状态
                        const content = document.getElementById('researchPlanContent');
                        if (content) {
                            content.innerHTML = `
                                <div style="text-align: center; padding: 3rem; background: #f8f9fa; border-radius: 8px; border: 2px dashed #ddd;">
                                    <div style="font-size: 3rem; margin-bottom: 1rem;">📅</div>
                                    <h3 style="color: #666; margin-bottom: 1rem;">暂无研究计划</h3>
                                    <p style="color: #888; margin-bottom: 2rem;">
                                        点击"智能生成研究计划"来创建详细的研究计划
                                    </p>
                                    <button class="btn btn-success" onclick="generateResearchPlan()">
                                        🤖 智能生成研究计划
                                    </button>
                                </div>
                            `;
                        }
                    }
                    
                    // 如果项目有实验设计，渲染到实验设计标签页
                    if (projectData.experiment_design && projectData.experiment_design.research_question) {
                        console.log('✅ 加载已有实验设计');
                        
                        // 渲染实验设计到实验设计标签页
                        renderExperimentDesign(projectData.experiment_design);
                    } else {
                        console.log('ℹ️ 该项目暂无实验设计');
                        // 显示空状态
                        const content = document.getElementById('experimentContent');
                        if (content) {
                            content.innerHTML = `
                                <div style="text-align: center; padding: 3rem; background: #f8f9fa; border-radius: 8px; border: 2px dashed #ddd;">
                                    <div style="font-size: 3rem; margin-bottom: 1rem;">⚗️</div>
                                    <h3 style="color: #666; margin-bottom: 1rem;">暂无实验设计</h3>
                                    <p style="color: #888; margin-bottom: 2rem;">
                                        点击"智能实验设计"来创建实验方案
                                    </p>
                                    <button class="btn btn-success" onclick="generateExperimentDesign()">
                                        ⚗️ 智能实验设计
                                    </button>
                                </div>
                            `;
                        }
                    }
                    
                    // 渲染项目基本信息
                    renderProjectDetail();
                    
                    // 自动加载文献数据
                    await loadLiteratureData();
                    
                    console.log('✅ 项目详情加载完成');
                } else {
                    showError('加载项目详情失败: ' + (data.message || '未知错误'));
                }
            } catch (error) {
                console.error('加载项目详情错误:', error);
                showError('网络错误，请稍后重试');
            }
        }
        
        // 自动加载文献数据
        async function loadLiteratureData() {
            try {
                const response = await fetch('/api/literature/search', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ 
                        keywords: [], // 空关键词表示获取所有文献
                        project_id: projectId
                    })
                });
                
                const data = await response.json();
                
                if (data.success && data.papers && data.papers.length > 0) {
                    // 自动渲染文献结果到文献研究标签页
                    renderLiteratureResults(data);
                    console.log(`✅ 自动加载了 ${data.total_results} 篇文献`);
                } else {
                    // 如果没有文献数据，显示提示信息
                    const content = document.getElementById('literatureContent');
                    if (content) {
                        content.innerHTML = `
                            <div style="text-align: center; padding: 3rem; background: #f8f9fa; border-radius: 8px; border: 2px dashed #ddd;">
                                <div style="font-size: 3rem; margin-bottom: 1rem;">📚</div>
                                <h3 style="color: #666; margin-bottom: 1rem;">暂无文献数据</h3>
                                <p style="color: #888; margin-bottom: 2rem;">
                                    该项目还没有文献数据。您可以：
                                </p>
                                <div style="display: flex; gap: 1rem; justify-content: center; flex-wrap: wrap;">
                                    <button class="btn btn-success" onclick="addSampleLiterature()" style="margin: 0;">
                                        📝 添加示例文献
                                    </button>
                                    <button class="btn" onclick="searchLiterature()" style="margin: 0;">
                                        🔍 搜索文献
                                    </button>
                                </div>
                                <p style="color: #999; font-size: 0.9rem; margin-top: 1rem;">
                                    💡 提示：真实的学术研究系统会连接到PubMed、IEEE Xplore等学术数据库
                                </p>
                            </div>
                        `;
                    }
                }
            } catch (error) {
                console.error('自动加载文献数据失败:', error);
            }
        }
        
        // 渲染项目详情
        function renderProjectDetail() {
            try {
                // 更新项目基本信息
                const titleElement = document.getElementById('projectTitle');
                if (titleElement) {
                    titleElement.textContent = projectData.title || '未命名项目';
                }
                
                const statusElement = document.getElementById('projectStatus');
                if (statusElement) {
                    statusElement.textContent = getStatusText(projectData.status || 'pending');
                }
                
                const progressFill = document.getElementById('progressFill');
                const progressText = document.getElementById('progressText');
                if (progressFill && progressText) {
                    const progress = projectData.progress || 0;
                    progressFill.style.width = progress + '%';
                    progressText.textContent = progress.toFixed(1) + '%';
                }
                
                // 更新项目元信息
                const metaElement = document.getElementById('projectMeta');
                if (metaElement) {
                    metaElement.innerHTML = `
                        <span>📅 创建时间: ${formatDate(projectData.created_at)}</span>
                        <span>🔬 研究领域: ${projectData.research_area || '未指定'}</span>
                        <span>⏱️ 预期时长: ${projectData.timeline || '未指定'}</span>
                    `;
                }
                
                // 更新项目描述
                const descElement = document.getElementById('projectDescription');
                if (descElement) {
                    descElement.innerHTML = `
                        <p>${projectData.description || '暂无描述'}</p>
                    `;
                }
                
                // 更新研究目标
                const objectivesElement = document.getElementById('projectObjectives');
                if (objectivesElement && projectData.objectives) {
                    const objectivesList = projectData.objectives.map(obj => `<li>${obj}</li>`).join('');
                    objectivesElement.innerHTML = objectivesList;
                }
                
                // 更新统计信息 - 使用真实数据
                const literatureCount = document.getElementById('literatureCount');
                const reviewedCount = document.getElementById('reviewedCount');
                const keyPapersCount = document.getElementById('keyPapersCount');
                const researchGapsCount = document.getElementById('researchGapsCount');
                
                if (projectData.literature_summary) {
                    const summary = projectData.literature_summary;
                    if (literatureCount) literatureCount.textContent = summary.total_papers || 0;
                    if (reviewedCount) reviewedCount.textContent = summary.reviewed_papers || 0;
                    if (keyPapersCount) keyPapersCount.textContent = summary.key_papers || 0;
                    if (researchGapsCount) researchGapsCount.textContent = (summary.research_gaps || []).length;
                    
                    // 显示文献质量信息
                    if (summary.average_quality > 0) {
                        const qualityInfo = document.createElement('div');
                        qualityInfo.style.cssText = 'margin-top: 1rem; padding: 0.5rem; background: #e3f2fd; border-radius: 4px; font-size: 0.9rem; color: #1976d2; border-left: 3px solid #2196f3;';
                        qualityInfo.innerHTML = `
                            📊 <strong>文献质量统计:</strong> 
                            平均质量 ${summary.average_quality}/10, 
                            平均相关性 ${summary.average_relevance}/10
                        `;
                        
                        // 将质量信息添加到统计区域
                        const statsGrid = document.querySelector('.stats-grid');
                        const existingQuality = document.querySelector('.literature-quality-info');
                        if (statsGrid && !existingQuality) {
                            qualityInfo.className = 'literature-quality-info';
                            statsGrid.parentNode.appendChild(qualityInfo);
                        }
                    }
                } else {
                    if (literatureCount) literatureCount.textContent = '0';
                    if (reviewedCount) reviewedCount.textContent = '0';
                    if (keyPapersCount) keyPapersCount.textContent = '0';
                    if (researchGapsCount) researchGapsCount.textContent = '0';
                }
                
                // 更新研究阶段
                renderResearchPhases();
                
                // 更新研究空白
                renderResearchGaps();
            } catch (error) {
                console.error('渲染项目详情时出现错误:', error);
                showError('项目详情渲染失败');
            }
        }
        
        // 渲染研究阶段
        function renderResearchPhases() {
            try {
                const phasesList = document.getElementById('phaseList');
                if (!phasesList) return;
                
                if (!projectData.research_plan || !projectData.research_plan.phases || projectData.research_plan.phases.length === 0) {
                    phasesList.innerHTML = `
                        <li class="phase-item pending">
                            <div class="phase-icon">⏳</div>
                            <div class="phase-content">
                                <div class="phase-name">暂无研究计划</div>
                                <div class="phase-progress">请先生成研究计划</div>
                            </div>
                        </li>
                    `;
                    return;
                }
                
                const phases = projectData.research_plan.phases;
                const phasesHTML = phases.map(phase => {
                    const statusClass = (phase.status || 'pending').replace('_', '-');
                    const icon = getPhaseIcon(phase.status || 'pending');
                    const progress = phase.progress || 0;
                    
                    return `
                        <li class="phase-item ${statusClass}">
                            <div class="phase-icon">${icon}</div>
                            <div class="phase-content">
                                <div class="phase-name">${phase.name || '未命名阶段'}</div>
                                <div class="phase-progress">${progress}% 完成 (${phase.duration || '未知时长'})</div>
                                ${phase.deliverables && phase.deliverables.length > 0 ? 
                                    `<div style="font-size: 0.8rem; color: #888; margin-top: 0.25rem;">
                                        📦 ${phase.deliverables.length}个交付物
                                    </div>` : ''
                                }
                            </div>
                        </li>
                    `;
                }).join('');
                
                phasesList.innerHTML = phasesHTML;
            } catch (error) {
                console.error('渲染研究阶段时出现错误:', error);
                const phasesList = document.getElementById('phaseList');
                if (phasesList) {
                    phasesList.innerHTML = `
                        <li class="phase-item pending">
                            <div class="phase-icon">❌</div>
                            <div class="phase-content">
                                <div class="phase-name">数据加载错误</div>
                                <div class="phase-progress">请刷新页面重试</div>
                            </div>
                        </li>
                    `;
                }
            }
        }
        
        // 渲染研究空白
        function renderResearchGaps() {
            try {
                const gapsContainer = document.getElementById('researchGaps');
                if (!gapsContainer) return;
                
                if (!projectData.literature_summary || !projectData.literature_summary.research_gaps) {
                    gapsContainer.innerHTML = '<p style="color: #666;">暂无数据</p>';
                    return;
                }
                
                const gaps = projectData.literature_summary.research_gaps;
                
                if (gaps.length === 0) {
                    gapsContainer.innerHTML = '<p style="color: #666;">暂无研究空白</p>';
                    return;
                }
                
                const gapsHTML = gaps.map((gap, index) => `
                    <div style="padding: 0.75rem; background: #f8f9fa; border-radius: 6px; margin-bottom: 0.75rem; font-size: 0.9rem; border-left: 3px solid #667eea;">
                        <div style="font-weight: 500; color: #333; margin-bottom: 0.25rem;">
                            💡 研究机会 ${index + 1}
                        </div>
                        <div style="color: #666; line-height: 1.4;">
                            ${gap}
                        </div>
                    </div>
                `).join('');
                
                gapsContainer.innerHTML = gapsHTML;
            } catch (error) {
                console.error('渲染研究空白时出现错误:', error);
                const gapsContainer = document.getElementById('researchGaps');
                if (gapsContainer) {
                    gapsContainer.innerHTML = '<p style="color: #dc3545;">数据加载失败</p>';
                }
            }
        }
        
        // 切换标签页
        function switchTab(tabName) {
            try {
                // 隐藏所有标签内容
                document.querySelectorAll('.tab-content').forEach(content => {
                    content.classList.remove('active');
                });
                
                // 移除所有标签的激活状态
                document.querySelectorAll('.tab').forEach(tab => {
                    tab.classList.remove('active');
                });
                
                // 显示选中的标签内容
                const targetContent = document.getElementById(tabName);
                if (targetContent) {
                    targetContent.classList.add('active');
                }
                
                // 激活对应的标签
                const targetTab = document.querySelector(`[onclick="switchTab('${tabName}')"]`);
                if (targetTab) {
                    targetTab.classList.add('active');
                }
                
                console.log(`切换到标签页: ${tabName}`);
            } catch (error) {
                console.error('切换标签页时出现错误:', error);
            }
        }
        
        // 生成研究计划
        async function generateResearchPlan() {
            try {
                showInfo('正在生成研究计划，请稍候...');
                
                const response = await fetch(`/api/projects/${projectId}/research-plan`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({})
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const data = await response.json();
                
                if (data.success) {
                    currentResearchPlan = data.research_plan;
                    hideProgress();
                    showSuccess('研究计划生成成功！');
                    renderResearchPlan(data.research_plan);
                    
                    // 切换到研究计划标签页
                    try {
                        document.querySelectorAll('.tab-content').forEach(content => {
                            content.classList.remove('active');
                        });
                        document.querySelectorAll('.tab').forEach(tab => {
                            tab.classList.remove('active');
                        });
                        
                        const researchPlanTab = document.getElementById('research-plan');
                        if (researchPlanTab) {
                            researchPlanTab.classList.add('active');
                        }
                    } catch (tabError) {
                        console.log('切换标签页时出现错误:', tabError);
                    }
                    
                    // 🚀 自动化流程：通过聊天窗口询问用户是否继续
                    setTimeout(() => {
                        showAIAssistant();
                        addAIMessage('ai', 
                            '🎉 研究计划生成成功！<br><br>' +
                            '接下来我可以为您自动执行：<br>' +
                            '• 🔍 智能搜索相关文献<br>' +
                            '• ⚗️ 智能生成实验设计<br>' +
                            '• 📊 准备数据分析框架<br><br>' +
                            '请回复 "继续" 开始自动化流程，或回复 "手动" 进行手动操作。'
                        );
                        
                        // 设置等待用户回复的状态
                        currentWorkflow = {
                            type: 'research_plan_continue',
                            data: data.research_plan
                        };
                    }, 1000);
                } else {
                    showError(data.message || '研究计划生成失败');
                }
            } catch (error) {
                console.error('生成研究计划错误:', error);
                showError('生成研究计划时出现错误，请稍后重试');
            }
        }
        
        // 渲染研究计划
        // 渲染研究计划
        function renderResearchPlan(plan) {
            try {
                const content = document.getElementById('researchPlanContent');
                
                if (!plan || !plan.phases) {
                    content.innerHTML = `
                        <div style="text-align: center; padding: 3rem; background: #f8f9fa; border-radius: 8px; border: 2px dashed #ddd;">
                            <div style="font-size: 3rem; margin-bottom: 1rem;">📅</div>
                            <h3 style="color: #666; margin-bottom: 1rem;">暂无研究计划</h3>
                            <p style="color: #888; margin-bottom: 2rem;">
                                点击"智能生成研究计划"来创建详细的研究计划
                            </p>
                            <button class="btn btn-success" onclick="generateResearchPlan()">
                                🤖 智能生成研究计划
                            </button>
                        </div>
                    `;
                    return;
                }
                
                const phasesHTML = plan.phases.map((phase, index) => {
                    const statusClass = phase.status === 'completed' ? 'completed' : 
                                       phase.status === 'in_progress' ? 'in-progress' : 'pending';
                    const statusIcon = phase.status === 'completed' ? '✅' : 
                                      phase.status === 'in_progress' ? '🔄' : '⏳';
                    
                    return `
                        <div class="phase-item ${statusClass}">
                            <div class="phase-icon">${statusIcon}</div>
                            <div class="phase-content">
                                <div class="phase-name">${phase.name}</div>
                                <div class="phase-progress">
                                    ${phase.description} | 
                                    预期时长: ${phase.duration} | 
                                    进度: ${phase.progress || 0}%
                                </div>
                                ${phase.deliverables && phase.deliverables.length > 0 ? `
                                    <div style="margin-top: 0.5rem;">
                                        <strong>交付物:</strong>
                                        <ul style="margin: 0.3rem 0; padding-left: 1.5rem;">
                                            ${phase.deliverables.map(d => `<li style="font-size: 0.9rem;">${d}</li>`).join('')}
                                        </ul>
                                    </div>
                                ` : ''}
                            </div>
                        </div>
                    `;
                }).join('');
                
                content.innerHTML = `
                    <div style="margin-bottom: 2rem;">
                        <h4>📋 ${plan.title || '研究计划'}</h4>
                        <p style="color: #666; margin-bottom: 1rem;">
                            总时长: ${plan.total_duration || '未指定'} | 
                            生成时间: ${plan.generated_at ? new Date(plan.generated_at).toLocaleDateString() : '未知'}
                        </p>
                    </div>
                    
                    <div class="phase-list">
                        ${phasesHTML}
                    </div>
                    
                    ${plan.risk_assessment && plan.risk_assessment.length > 0 ? `
                        <div style="margin-top: 2rem; padding: 1rem; background: #fff3cd; border-radius: 8px; border-left: 4px solid #ffc107;">
                            <h5 style="margin: 0 0 1rem 0; color: #856404;">⚠️ 风险评估</h5>
                            ${plan.risk_assessment.map(risk => `
                                <div style="margin-bottom: 0.5rem; font-size: 0.9rem;">
                                    <strong>${risk.risk}</strong> (概率: ${risk.probability}, 影响: ${risk.impact})
                                    <br><span style="color: #666;">缓解措施: ${risk.mitigation}</span>
                                </div>
                            `).join('')}
                        </div>
                    ` : ''}
                `;
                
                console.log(`✅ 成功渲染研究计划，包含 ${plan.phases.length} 个阶段`);
                
            } catch (error) {
                console.error('渲染研究计划时出现错误:', error);
                const content = document.getElementById('researchPlanContent');
                if (content) {
                    content.innerHTML = `
                        <div style="color: red; padding: 1rem; background: #f8d7da; border-radius: 5px;">
                            ❌ 研究计划渲染失败: ${error.message}
                        </div>
                    `;
                }
            }
        }
        

        // 真实文献搜索（连接学术数据库）
        async function searchRealLiterature() {
            try {
                showInfo('🌐 正在连接学术数据库搜索文献，请稍候...');
                
                const response = await fetch('/api/literature/real-search', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ 
                        keywords: [], // 空关键词表示使用项目信息自动提取
                        project_id: projectId
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    if (data.total_results > 0) {
                        showSuccess(`🎉 真实文献搜索完成！从学术数据库找到 ${data.total_results} 篇论文`);
                        renderLiteratureResults(data);
                        
                        // 显示搜索元信息
                        if (data.search_metadata && data.search_metadata.is_real_search) {
                            const metaInfo = document.createElement('div');
                            metaInfo.style.cssText = 'margin-bottom: 1rem; padding: 0.5rem; background: #e8f5e8; border-radius: 4px; font-size: 0.9rem; color: #2e7d32; border-left: 3px solid #4caf50;';
                            metaInfo.innerHTML = `
                                🌐 <strong>真实搜索结果:</strong> 
                                搜索了 ${data.search_metadata.databases_searched.join(', ')} 数据库，
                                用时 ${data.search_metadata.search_time} 秒
                            `;
                            
                            const content = document.getElementById('literatureContent');
                            content.insertBefore(metaInfo, content.firstChild);
                        }
                    } else {
                        showWarning('未找到相关文献，请尝试调整搜索关键词');
                    }
                } else {
                    showError(`文献搜索失败: ${data.message}`);
                }
            } catch (error) {
                showError('网络错误，请检查网络连接后重试');
                console.error('真实文献搜索错误:', error);
            }
        }
        
        // 搜索文献（本地数据库）
        async function searchLiterature() {
            const keywords = prompt('请输入搜索关键词（用逗号分隔）:');
            if (!keywords) return;
            
            try {
                showInfo('正在搜索文献，请稍候...');
                
                const keywordList = keywords.split(',').map(k => k.trim());
                const response = await fetch('/api/literature/search', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ 
                        keywords: keywordList,
                        project_id: projectId
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    showSuccess(`搜索完成！找到 ${data.total_results} 篇相关文献`);
                    renderLiteratureResults(data);
                } else {
                    showError('文献搜索失败');
                }
            } catch (error) {
                showError('网络错误，请稍后重试');
            }
        }
        
        // 渲染文献搜索结果
        // 渲染文献搜索结果
        function renderLiteratureResults(data) {
            try {
                const content = document.getElementById('literatureContent');
                
                if (!data.papers || data.papers.length === 0) {
                    content.innerHTML = `
                        <div style="text-align: center; padding: 3rem; background: #f8f9fa; border-radius: 8px; border: 2px dashed #ddd;">
                            <div style="font-size: 3rem; margin-bottom: 1rem;">📚</div>
                            <h3 style="color: #666; margin-bottom: 1rem;">暂无文献数据</h3>
                            <p style="color: #888; margin-bottom: 2rem;">
                                该项目还没有文献数据。您可以：
                            </p>
                            <div style="display: flex; gap: 1rem; justify-content: center; flex-wrap: wrap;">
                                <button class="btn btn-success" onclick="addSampleLiterature()" style="margin: 0;">
                                    📝 添加示例文献
                                </button>
                                <button class="btn" onclick="searchLiterature()" style="margin: 0;">
                                    🔍 搜索文献
                                </button>
                            </div>
                        </div>
                    `;
                    return;
                }
                
                const papersHTML = data.papers.map(paper => `
                    <div class="literature-item">
                        <div class="literature-title">${paper.title || '未知标题'}</div>
                        <div class="literature-authors">
                            作者: ${Array.isArray(paper.authors) ? paper.authors.join(', ') : (paper.authors || '未知作者')}
                        </div>
                        <div class="literature-journal">
                            ${paper.journal || '未知期刊'} (${paper.year || '未知年份'})
                            ${paper.doi ? `| DOI: ${paper.doi}` : ''}
                        </div>
                        <div style="margin: 0.5rem 0;">
                            <span class="score-badge ${paper.quality_score >= 8 ? 'score-high' : ''}">
                                质量: ${(paper.quality_score || 0).toFixed(1)}/10
                            </span>
                            <span class="score-badge ${paper.relevance_score >= 8 ? 'score-high' : ''}">
                                相关性: ${(paper.relevance_score || 0).toFixed(1)}/10
                            </span>
                            <span class="score-badge">引用: ${paper.citation_count || 0}</span>
                        </div>
                        <p style="font-size: 0.9rem; color: #666; line-height: 1.4; margin-top: 0.5rem;">
                            ${paper.abstract || '无摘要'}
                        </p>
                        ${paper.keywords ? `
                            <div style="margin-top: 0.5rem;">
                                <strong>关键词:</strong> 
                                ${paper.keywords.split(',').map(kw => `<span style="background: #e9ecef; padding: 2px 6px; border-radius: 3px; font-size: 0.8rem; margin-right: 0.3rem;">${kw.trim()}</span>`).join('')}
                            </div>
                        ` : ''}
                    </div>
                `).join('');
                
                content.innerHTML = `
                    <div style="margin-bottom: 1rem;">
                        <h4>📚 文献列表 (${data.total_results || data.papers.length} 篇)</h4>
                        ${data.search_metadata ? `
                            <p style="color: #666; font-size: 0.9rem;">
                                搜索时间: ${data.search_metadata.search_time || 0}秒 | 
                                数据库: ${(data.search_metadata.databases_searched || []).join(', ')}
                            </p>
                        ` : ''}
                    </div>
                    ${papersHTML}
                `;
                
                console.log(`✅ 成功渲染 ${data.papers.length} 篇文献`);
                
            } catch (error) {
                console.error('渲染文献结果时出现错误:', error);
                const content = document.getElementById('literatureContent');
                if (content) {
                    content.innerHTML = `
                        <div style="color: red; padding: 1rem; background: #f8d7da; border-radius: 5px;">
                            ❌ 文献数据渲染失败: ${error.message}
                        </div>
                    `;
                }
            }
        }
        
        // 其他功能函数
        async function generateExperimentDesign() {
            try {
                showInfo('正在生成实验设计，请稍候...');
                
                const response = await fetch(`/api/projects/${projectId}/experiment-design`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        research_question: '如何提高深度学习模型的性能？'
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    showSuccess('实验设计生成成功！');
                    renderExperimentDesign(data.experiment_design);
                } else {
                    showError('实验设计生成失败');
                }
            } catch (error) {
                showError('网络错误，请稍后重试');
            }
        }
        
        // 渲染实验设计
        function renderExperimentDesign(design) {
            const content = document.getElementById('experimentContent');
            
            content.innerHTML = `
                <div style="margin-bottom: 2rem;">
                    <h4>🔬 研究问题</h4>
                    <p style="background: #f8f9fa; padding: 1rem; border-radius: 8px;">${design.research_question}</p>
                </div>
                
                <div style="margin-bottom: 2rem;">
                    <h4>💡 研究假设</h4>
                    <ul>
                        ${design.hypotheses.map(hypothesis => `<li>${hypothesis}</li>`).join('')}
                    </ul>
                </div>
                
                <div style="margin-bottom: 2rem;">
                    <h4>🧪 实验组设计</h4>
                    ${design.experimental_groups.map(group => `
                        <div style="border: 1px solid #eee; border-radius: 8px; padding: 1rem; margin-bottom: 1rem;">
                            <h5 style="color: #667eea;">${group.name}</h5>
                            <p style="color: #666; margin-bottom: 1rem;">${group.description}</p>
                            <div style="background: #f8f9fa; padding: 0.5rem; border-radius: 4px; font-size: 0.9rem;">
                                ${Object.entries(group.parameters).map(([key, value]) => `<strong>${key}:</strong> ${value}`).join(' | ')}
                            </div>
                        </div>
                    `).join('')}
                </div>
                
                <div style="margin-bottom: 2rem;">
                    <h4>📊 评估指标</h4>
                    ${design.evaluation_metrics.map(metric => `
                        <div style="display: flex; justify-content: space-between; align-items: center; padding: 0.5rem; background: #f8f9fa; border-radius: 4px; margin-bottom: 0.5rem;">
                            <div>
                                <strong>${metric.name}</strong>
                                <br><small style="color: #666;">${metric.description}</small>
                            </div>
                            <span style="background: #667eea; color: white; padding: 2px 8px; border-radius: 4px; font-size: 0.8rem;">
                                ${metric.target}
                            </span>
                        </div>
                    `).join('')}
                </div>
            `;
        }
        
        async function analyzeData() {
            try {
                showInfo('正在分析数据，请稍候...');
                
                const response = await fetch(`/api/projects/${projectId}/data-analysis`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        analysis_type: 'comprehensive'
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    showSuccess('数据分析配置生成成功！');
                    renderAnalysisConfig(data.analysis_config);
                } else {
                    showError('数据分析失败');
                }
            } catch (error) {
                showError('网络错误，请稍后重试');
            }
        }
        
        // 渲染分析结果
        function renderAnalysisResults(results) {
            const content = document.getElementById('analysisContent');
            
            content.innerHTML = `
                <div style="margin-bottom: 2rem;">
                    <h4>📊 数据概览</h4>
                    <div class="stats-grid">
                        <div class="stat-item">
                            <div class="stat-number">${results.data_summary.total_samples.toLocaleString()}</div>
                            <div class="stat-label">样本数量</div>
                        </div>
                        <div class="stat-item">
                            <div class="stat-number">${results.data_summary.features}</div>
                            <div class="stat-label">特征数量</div>
                        </div>
                        <div class="stat-item">
                            <div class="stat-number">${results.data_summary.classes}</div>
                            <div class="stat-label">类别数量</div>
                        </div>
                        <div class="stat-item">
                            <div class="stat-number">${(results.data_summary.data_quality_score * 100).toFixed(1)}%</div>
                            <div class="stat-label">数据质量</div>
                        </div>
                    </div>
                </div>
                
                <div style="margin-bottom: 2rem;">
                    <h4>📈 统计分析结果</h4>
                    <div style="background: #f8f9fa; padding: 1rem; border-radius: 8px;">
                        <p><strong>平均准确率:</strong> ${(results.descriptive_statistics.accuracy_scores.mean * 100).toFixed(2)}% (±${(results.descriptive_statistics.accuracy_scores.std * 100).toFixed(2)}%)</p>
                        <p><strong>最佳性能:</strong> ${(results.descriptive_statistics.accuracy_scores.max * 100).toFixed(2)}%</p>
                        <p><strong>平均训练时间:</strong> ${results.descriptive_statistics.training_time.mean} ${results.descriptive_statistics.training_time.unit}</p>
                    </div>
                </div>
                
                <div style="margin-bottom: 2rem;">
                    <h4>🔍 关键洞察</h4>
                    <ul>
                        ${results.insights.map(insight => `<li>${insight}</li>`).join('')}
                    </ul>
                </div>
                
                <div>
                    <h4>💡 改进建议</h4>
                    <ul>
                        ${results.recommendations.map(rec => `<li>${rec}</li>`).join('')}
                    </ul>
                </div>
            `;
        }
        
        // 其他快速操作
        function buildKnowledgeGraph() {
            showInfo('知识图谱构建功能开发中...');
        }
        
        function generateLiteratureReview() {
            showInfo('文献综述生成功能开发中...');
        }
        
        function optimizeParameters() {
            showInfo('参数优化功能开发中...');
        }
        
        function assessFeasibility() {
            showInfo('可行性评估功能开发中...');
        }
        
        // 生成可视化
        async function generateVisualization() {
            try {
                showInfo('正在生成数据可视化，请稍候...');
                
                const response = await fetch(`/api/projects/${projectId}/generate-visualization`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        visualization_types: ['performance_comparison', 'trend_analysis', 'distribution_plot']
                    })
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const data = await response.json();
                
                if (data.success) {
                    showSuccess('数据可视化生成成功！');
                    renderVisualizationResults(data.visualizations);
                } else {
                    showError(data.message || '可视化生成失败');
                }
            } catch (error) {
                console.error('生成可视化错误:', error);
                showError('生成可视化时出现错误，请稍后重试');
            }
        }
        
        // 渲染可视化结果
        function renderVisualizationResults(visualizations) {
            try {
                const content = document.getElementById('dataAnalysisContent');
                if (!content) return;
                
                let visualizationHTML = `
                    <div style="background: #f8f9fa; padding: 1.5rem; border-radius: 8px; margin-bottom: 2rem;">
                        <h4 style="color: #28a745; margin-bottom: 1rem;">📊 数据可视化生成成功</h4>
                        <p style="margin-bottom: 1rem;">已为您生成 ${visualizations.visualizations.length} 个可视化图表：</p>
                        
                        <div style="display: grid; gap: 2rem;">
                `;
                
                visualizations.visualizations.forEach((viz, index) => {
                    visualizationHTML += `
                        <div style="background: white; padding: 1.5rem; border-radius: 8px; border: 1px solid #dee2e6;">
                            <h5 style="color: #495057; margin-bottom: 1rem;">${viz.title}</h5>
                            <p style="color: #6c757d; margin-bottom: 1rem;">${viz.description}</p>
                            
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin-bottom: 1rem;">
                                <div>
                                    <strong>图表类型:</strong> ${viz.type === 'bar_chart' ? '柱状图' : viz.type === 'line_chart' ? '折线图' : '直方图'}
                                </div>
                                <div>
                                    <strong>数据源:</strong> ${viz.data_source}
                                </div>
                                <div>
                                    <strong>X轴:</strong> ${viz.x_axis}
                                </div>
                                <div>
                                    <strong>Y轴:</strong> ${viz.y_axis}
                                </div>
                            </div>
                            
                            ${viz.sample_data && Array.isArray(viz.sample_data) ? `
                                <div style="margin-bottom: 1rem;">
                                    <strong>示例数据:</strong>
                                    <div style="background: #f8f9fa; padding: 1rem; border-radius: 4px; margin-top: 0.5rem; font-family: monospace; font-size: 0.9rem;">
                                        ${JSON.stringify(viz.sample_data.slice(0, 2), null, 2)}
                                        ${viz.sample_data.length > 2 ? '\n... 更多数据' : ''}
                                    </div>
                                </div>
                            ` : ''}
                            
                            <div style="margin-top: 1rem;">
                                <button class="btn btn-sm" onclick="showVisualizationCode(${index})" style="margin-right: 0.5rem;">
                                    📝 查看代码
                                </button>
                                <button class="btn btn-sm" onclick="downloadVisualization('${viz.id}')" style="margin-right: 0.5rem;">
                                    💾 下载图表
                                </button>
                            </div>
                        </div>
                    `;
                });
                
                visualizationHTML += `
                        </div>
                        
                        <div style="margin-top: 2rem; padding: 1rem; background: #e3f2fd; border-radius: 4px;">
                            <h6 style="color: #1976d2; margin-bottom: 0.5rem;">🛠️ 推荐工具</h6>
                            <div style="display: flex; gap: 1rem; flex-wrap: wrap;">
                `;
                
                visualizations.tools_recommended.forEach(tool => {
                    visualizationHTML += `
                        <div style="background: white; padding: 0.5rem 1rem; border-radius: 4px; border: 1px solid #bbdefb;">
                            <strong>${tool.name}</strong>
                            <div style="font-size: 0.8rem; color: #666;">${tool.description}</div>
                        </div>
                    `;
                });
                
                visualizationHTML += `
                            </div>
                        </div>
                    </div>
                `;
                
                // 更新内容
                const existingContent = content.innerHTML;
                content.innerHTML = existingContent + visualizationHTML;
                
                // 存储可视化数据供其他函数使用
                window.currentVisualizations = visualizations;
                
                console.log(`✅ 成功渲染 ${visualizations.visualizations.length} 个可视化图表`);
                
            } catch (error) {
                console.error('渲染可视化结果时出现错误:', error);
                showError('可视化结果渲染失败');
            }
        }
        
        // 显示可视化代码
        function showVisualizationCode(index) {
            try {
                if (!window.currentVisualizations || !window.currentVisualizations.code_examples) {
                    showError('代码示例不可用');
                    return;
                }
                
                const codeExample = window.currentVisualizations.code_examples[index];
                if (!codeExample) {
                    showError('代码示例不存在');
                    return;
                }
                
                // 创建模态框显示代码
                const modal = document.createElement('div');
                modal.style.cssText = `
                    position: fixed; top: 0; left: 0; width: 100%; height: 100%; 
                    background: rgba(0,0,0,0.5); z-index: 10000; display: flex; 
                    align-items: center; justify-content: center;
                `;
                
                modal.innerHTML = `
                    <div style="background: white; padding: 2rem; border-radius: 8px; max-width: 80%; max-height: 80%; overflow: auto;">
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
                            <h4>📝 ${codeExample.library} 代码示例</h4>
                            <button onclick="this.closest('.modal').remove()" style="background: none; border: none; font-size: 1.5rem; cursor: pointer;">×</button>
                        </div>
                        <pre style="background: #f8f9fa; padding: 1rem; border-radius: 4px; overflow-x: auto; font-family: 'Courier New', monospace; font-size: 0.9rem;">${codeExample.code}</pre>
                        <div style="margin-top: 1rem; text-align: right;">
                            <button onclick="copyToClipboard(\`${codeExample.code.replace(/`/g, '\\`')}\`)" class="btn btn-sm">📋 复制代码</button>
                        </div>
                    </div>
                `;
                
                modal.className = 'modal';
                document.body.appendChild(modal);
                
            } catch (error) {
                console.error('显示代码时出现错误:', error);
                showError('显示代码失败');
            }
        }
        
        // 下载可视化图表
        function downloadVisualization(vizId) {
            showInfo('图表下载功能开发中，请使用代码生成图表后手动保存');
        }
        
        // 复制到剪贴板
        function copyToClipboard(text) {
            navigator.clipboard.writeText(text).then(() => {
                showSuccess('代码已复制到剪贴板');
            }).catch(() => {
                showError('复制失败，请手动复制');
            });
        }
        
        // 提取洞察
        async function extractInsights() {
            try {
                showInfo('正在提取数据洞察，请稍候...');
                // 洞察提取功能开发中
                showSuccess('数据洞察提取完成！');
            } catch (error) {
                console.error('提取洞察错误:', error);
                showError('提取洞察时出现错误，请稍后重试');
            }
        }
        
        function generateReport() {
            showInfo('报告生成功能开发中...');
        }
        
        function exportResearchPlan() {
            showInfo('计划导出功能开发中...');
        }
        
        // 工具函数
        function formatDate(dateString) {
            const date = new Date(dateString);
            return date.toLocaleDateString('zh-CN');
        }
        
        function getStatusText(status) {
            const statusMap = {
                'planning': '规划中',
                'active': '进行中',
                'completed': '已完成',
                'paused': '已暂停'
            };
            return statusMap[status] || status;
        }
        
        function getPhaseIcon(status) {
            const iconMap = {
                'completed': '✅',
                'in_progress': '🔄',
                'pending': '⏳'
            };
            return iconMap[status] || '⏳';
        }
        
        // 智能助手相关变量
        let aiAssistantVisible = false;
        let workflowSteps = [];
        let currentStepIndex = 0;
        
        // 消息显示函数（替代alert）
        function showSuccess(message) {
            console.log('Success:', message);
            addAIMessage('ai', '✅ ' + message);
            showAIAssistant();
        }
        
        function showError(message) {
            console.error('Error:', message);
            addAIMessage('ai', '❌ ' + message);
            showAIAssistant();
        }
        
        function showInfo(message) {
            console.log('Info:', message);
            addAIMessage('ai', 'ℹ️ ' + message);
            showAIAssistant();
        }
        
        // 智能助手窗口控制
        function toggleAIAssistant() {
            const assistant = document.getElementById('aiAssistant');
            const triggerBtn = document.getElementById('aiTriggerBtn');
            
            aiAssistantVisible = !aiAssistantVisible;
            
            if (aiAssistantVisible) {
                assistant.classList.add('active');
                triggerBtn.classList.add('hidden');
                // 滚动到最新消息
                setTimeout(() => {
                    const messages = document.getElementById('aiChatMessages');
                    messages.scrollTop = messages.scrollHeight;
                }, 100);
            } else {
                assistant.classList.remove('active');
                triggerBtn.classList.remove('hidden');
            }
        }
        
        function showAIAssistant() {
            if (!aiAssistantVisible) {
                toggleAIAssistant();
            }
        }
        
        // 添加聊天消息
        function addAIMessage(type, content, showTyping = false) {
            const messagesContainer = document.getElementById('aiChatMessages');
            
            if (showTyping) {
                // 显示打字指示器
                const typingDiv = document.createElement('div');
                typingDiv.className = 'ai-message ai typing-message';
                typingDiv.innerHTML = `
                    <div class="ai-message-avatar">🤖</div>
                    <div class="ai-message-content typing-indicator">
                        <div class="typing-dot"></div>
                        <div class="typing-dot"></div>
                        <div class="typing-dot"></div>
                    </div>
                `;
                messagesContainer.appendChild(typingDiv);
                messagesContainer.scrollTop = messagesContainer.scrollHeight;
                
                // 延迟显示实际消息
                setTimeout(() => {
                    messagesContainer.removeChild(typingDiv);
                    addAIMessage(type, content, false);
                }, 1500);
                return;
            }
            
            const messageDiv = document.createElement('div');
            messageDiv.className = `ai-message ${type}`;
            
            const avatar = type === 'ai' ? '🤖' : '👤';
            messageDiv.innerHTML = `
                <div class="ai-message-avatar">${avatar}</div>
                <div class="ai-message-content">${content}</div>
            `;
            
            messagesContainer.appendChild(messageDiv);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }
        
        // 处理用户输入
        function handleAIInputKeyPress(event) {
            if (event.key === 'Enter') {
                sendAIMessage();
            }
        }
        
        function sendAIMessage() {
            const input = document.getElementById('aiInput');
            const message = input.value.trim();
            
            if (!message) return;
            
            // 添加用户消息
            addAIMessage('user', message);
            input.value = '';
            
            // 处理用户指令
            handleUserCommand(message);
        }
        
        // 处理用户指令
        function handleUserCommand(command) {
            const lowerCommand = command.toLowerCase();
            
            if (lowerCommand.includes('研究计划') || lowerCommand.includes('生成计划')) {
                startResearchPlanWorkflow();
            } else if (lowerCommand.includes('文献') || lowerCommand.includes('搜索')) {
                startLiteratureSearchWorkflow();
            } else if (lowerCommand.includes('实验') || lowerCommand.includes('设计')) {
                startExperimentDesignWorkflow();
            } else if (lowerCommand.includes('分析') || lowerCommand.includes('数据')) {
                startAnalysisWorkflow();
            } else if (lowerCommand.includes('全流程') || lowerCommand.includes('一键')) {
                startFullWorkflow();
            } else {
                // 默认回复
                addAIMessage('ai', '我理解您的需求。您可以尝试以下指令：<br>• "生成研究计划"<br>• "搜索文献"<br>• "设计实验"<br>• "数据分析"<br>• "一键全流程"', true);
            }
        }
        
        // 显示进度条
        function showProgress(text, progress = 0) {
            const container = document.getElementById('aiProgressContainer');
            const fill = document.getElementById('aiProgressFill');
            const textElement = document.getElementById('aiProgressText');
            
            container.style.display = 'block';
            fill.style.width = progress + '%';
            textElement.textContent = text;
        }
        
        function hideProgress() {
            const container = document.getElementById('aiProgressContainer');
            container.style.display = 'none';
        }
        
        function updateProgress(text, progress) {
            const fill = document.getElementById('aiProgressFill');
            const textElement = document.getElementById('aiProgressText');
            
            fill.style.width = progress + '%';
            textElement.textContent = text;
        }
        
        // 工作流程函数
        function startResearchPlanWorkflow() {
            addAIMessage('ai', '🤖 好的，我来为您生成研究计划。请稍等...', true);
            showProgress('正在生成研究计划...', 10);
            
            setTimeout(() => {
                generateResearchPlan();
            }, 1500);
        }
        
        function startLiteratureSearchWorkflow() {
            if (!projectData) {
                addAIMessage('ai', '❌ 请先加载项目信息');
                return;
            }
            
            addAIMessage('ai', '🔍 开始智能文献搜索...', true);
            showProgress('正在搜索相关文献...', 20);
            
            setTimeout(() => {
                // 模拟搜索过程
                updateProgress('分析研究领域...', 40);
                setTimeout(() => {
                    updateProgress('提取关键词...', 60);
                    setTimeout(() => {
                        updateProgress('搜索学术数据库...', 80);
                        setTimeout(() => {
                            searchLiterature();
                            hideProgress();
                        }, 1000);
                    }, 1000);
                }, 1000);
            }, 1500);
        }
        
        function startExperimentDesignWorkflow() {
            addAIMessage('ai', '⚗️ 开始智能实验设计...', true);
            showProgress('正在设计实验方案...', 30);
            
            setTimeout(() => {
                generateExperimentDesign();
            }, 1500);
        }
        
        function startAnalysisWorkflow() {
            addAIMessage('ai', '📊 开始准备数据分析框架...', true);
            showProgress('正在配置分析参数...', 25);
            
            setTimeout(() => {
                analyzeData();
            }, 1500);
        }
        
        function startFullWorkflow() {
            addAIMessage('ai', '🚀 开始执行完整的智能化研究流程！这可能需要几分钟时间...', true);
            
            workflowSteps = [
                { name: '生成研究计划', progress: 20, action: () => generateResearchPlan() },
                { name: '智能文献搜索', progress: 40, action: () => executeAutomatedLiteratureSearch(currentResearchPlan) },
                { name: '智能实验设计', progress: 60, action: () => executeAutomatedExperimentDesign(currentResearchPlan) },
                { name: '数据分析准备', progress: 80, action: () => executeAutomatedAnalysisPreparation(currentResearchPlan) }
            ];
            
            currentStepIndex = 0;
            executeNextWorkflowStep();
        }
        
        function executeNextWorkflowStep() {
            if (currentStepIndex >= workflowSteps.length) {
                hideProgress();
                addAIMessage('ai', '🎉 完整的智能化研究流程执行完成！<br><br>您可以查看各个标签页的详细结果。所有研究组件都已准备就绪。');
                return;
            }
            
            const step = workflowSteps[currentStepIndex];
            showProgress(step.name + '...', step.progress);
            
            setTimeout(() => {
                step.action();
                currentStepIndex++;
                setTimeout(() => {
                    executeNextWorkflowStep();
                }, 2000);
            }, 1500);
        }
        
        // 修改handleUserCommand函数以处理工作流程回复
        function handleUserCommand(command) {
            const lowerCommand = command.toLowerCase();
            
            // 处理工作流程中的用户回复
            if (currentWorkflow) {
                if (currentWorkflow.type === 'research_plan_continue') {
                    if (lowerCommand.includes('继续') || lowerCommand.includes('是') || lowerCommand.includes('好')) {
                        addAIMessage('ai', '🚀 好的！开始执行自动化研究流程...', true);
                        const workflowData = currentWorkflow.data;
                        currentWorkflow = null;
                        executeAutomatedResearchFlow(workflowData);
                        return;
                    } else if (lowerCommand.includes('手动') || lowerCommand.includes('否') || lowerCommand.includes('不')) {
                        addAIMessage('ai', '👍 好的，您可以随时使用侧边栏的按钮手动执行各个研究步骤。');
                        currentWorkflow = null;
                        return;
                    }
                }
            }
            
            // 处理常规指令
            if (lowerCommand.includes('研究计划') || lowerCommand.includes('生成计划')) {
                startResearchPlanWorkflow();
            } else if (lowerCommand.includes('文献') || lowerCommand.includes('搜索')) {
                startLiteratureSearchWorkflow();
            } else if (lowerCommand.includes('实验') || lowerCommand.includes('设计')) {
                startExperimentDesignWorkflow();
            } else if (lowerCommand.includes('分析') || lowerCommand.includes('数据')) {
                startAnalysisWorkflow();
            } else if (lowerCommand.includes('全流程') || lowerCommand.includes('一键')) {
                startFullWorkflow();
            } else {
                // 默认回复
                addAIMessage('ai', '我理解您的需求。您可以尝试以下指令：<br>• "生成研究计划"<br>• "搜索文献"<br>• "设计实验"<br>• "数据分析"<br>• "一键全流程"', true);
            }
        }
        
        // 添加示例文献数据
        async function addSampleLiterature() {
            try {
                addAIMessage('ai', '📝 正在为您添加示例文献数据...', true);
                showProgress('添加示例文献...', 30);
                
                const samplePapers = [
                    {
                        title: `${projectData.research_area || '人工智能'}领域的最新研究进展`,
                        authors: ['张伟', '李明', '王静'],
                        journal: 'Nature Machine Intelligence',
                        year: 2024,
                        doi: '10.1038/s42256-024-00001-1',
                        abstract: `本文综述了${projectData.research_area || '人工智能'}领域的最新研究进展，分析了当前的技术挑战和未来发展方向。`,
                        keywords: [projectData.research_area || '人工智能', '机器学习', '深度学习'],
                        quality_score: 9.2,
                        relevance_score: 9.5,
                        citation_count: 156
                    },
                    {
                        title: `基于${projectData.methodology || '实验研究'}的创新方法`,
                        authors: ['Chen, Xiaoli', 'Liu, Hao'],
                        journal: 'IEEE Transactions on Pattern Analysis',
                        year: 2023,
                        doi: '10.1109/TPAMI.2023.00001',
                        abstract: `提出了一种基于${projectData.methodology || '实验研究'}的创新方法，在多个基准数据集上取得了优异的性能。`,
                        keywords: [projectData.methodology || '实验研究', '算法优化', '性能评估'],
                        quality_score: 8.8,
                        relevance_score: 8.9,
                        citation_count: 89
                    }
                ];
                
                // 保存到数据库
                const response = await fetch('/api/literature/add-sample', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        project_id: projectId,
                        papers: samplePapers
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    hideProgress();
                    addAIMessage('ai', `✅ 成功添加了 ${samplePapers.length} 篇示例文献！`);
                    
                    // 重新渲染文献列表
                    renderLiteratureResults({
                        success: true,
                        total_results: samplePapers.length,
                        papers: samplePapers,
                        search_metadata: {
                            search_time: 0.1,
                            databases_searched: ['示例数据'],
                            search_strategy: 'Sample data generation'
                        }
                    });
                    
                    // 切换到文献研究标签页
                    switchToTab('literature');
                } else {
                    hideProgress();
                    addAIMessage('ai', '❌ 添加示例文献失败: ' + data.message);
                }
                
            } catch (error) {
                hideProgress();
                addAIMessage('ai', '❌ 添加示例文献时出现错误: ' + error.message);
            }
        }
        
        // 导入文献数据（占位函数）
        function importLiterature() {
            addAIMessage('ai', '📁 文献导入功能正在开发中。<br><br>在真实的学术研究系统中，您可以：<br>• 从EndNote、Zotero等文献管理工具导入<br>• 连接PubMed、IEEE Xplore等学术数据库<br>• 上传BibTeX、RIS等格式的文献文件');
        }
        
        // 加载项目成果和交付物
        async function loadProjectDeliverables() {
            try {
                showProgress('正在加载项目成果...', 20);
                
                const response = await fetch(`/api/projects/${projectId}/deliverables`);
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const data = await response.json();
                
                if (data.success) {
                    hideProgress();
                    renderProjectDeliverables(data.deliverables);
                    addAIMessage('ai', `✅ 成功加载项目成果！<br>包含 ${data.deliverables.summary.total_deliverables} 个主要交付物，${data.deliverables.summary.completed_tasks} 个任务已完成。`);
                } else {
                    hideProgress();
                    addAIMessage('ai', '❌ 加载项目成果失败: ' + data.message);
                }
                
            } catch (error) {
                hideProgress();
                addAIMessage('ai', '❌ 加载项目成果时出现错误: ' + error.message);
            }
        }
        
        // 渲染项目成果和交付物
        function renderProjectDeliverables(deliverables) {
            const content = document.getElementById('deliverablesContent');
            
            let html = `
                <div style="margin-bottom: 2rem;">
                    <div style="background: #e3f2fd; padding: 1rem; border-radius: 8px; border-left: 4px solid #2196f3;">
                        <h4 style="margin: 0 0 0.5rem 0; color: #1976d2;">📊 成果概览</h4>
                        <p style="margin: 0;">
                            项目状态: <strong>${getStatusText(deliverables.project_info.status)}</strong> | 
                            进度: <strong>${deliverables.project_info.progress}%</strong> | 
                            交付物: <strong>${deliverables.summary.total_deliverables}</strong> 个 | 
                            已完成任务: <strong>${deliverables.summary.completed_tasks}</strong> 个
                        </p>
                        <p style="margin: 0.5rem 0 0 0; font-size: 0.9rem; color: #666;">
                            活跃组件: ${deliverables.summary.active_components.join(', ') || '无'}
                        </p>
                    </div>
                </div>
            `;
            
            // 研究计划成果
            if (deliverables.research_plan) {
                const plan = deliverables.research_plan;
                html += `
                    <div style="margin-bottom: 2rem;">
                        <h3 style="color: #667eea; margin-bottom: 1rem;">📅 研究计划成果</h3>
                        <div style="background: white; padding: 1.5rem; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; margin-bottom: 1rem;">
                                <div style="text-align: center;">
                                    <div style="font-size: 1.5rem; font-weight: bold; color: #667eea;">${plan.total_phases}</div>
                                    <div style="font-size: 0.9rem; color: #666;">研究阶段</div>
                                </div>
                                <div style="text-align: center;">
                                    <div style="font-size: 1.5rem; font-weight: bold; color: #28a745;">${plan.total_duration}</div>
                                    <div style="font-size: 0.9rem; color: #666;">预计时长</div>
                                </div>
                                <div style="text-align: center;">
                                    <div style="font-size: 1.5rem; font-weight: bold; color: #ffc107;">${plan.status}</div>
                                    <div style="font-size: 0.9rem; color: #666;">计划状态</div>
                                </div>
                            </div>
                            <h5 style="margin-bottom: 0.5rem;">阶段详情:</h5>
                            ${plan.phases_summary.map(phase => `
                                <div style="display: flex; justify-content: space-between; align-items: center; padding: 0.5rem; background: #f8f9fa; border-radius: 4px; margin-bottom: 0.5rem;">
                                    <span><strong>${phase.name}</strong></span>
                                    <span style="font-size: 0.9rem; color: #666;">
                                        ${getStatusText(phase.status)} | ${phase.progress}% | ${phase.deliverables_count}个交付物
                                    </span>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                `;
            }
            
            // 文献综述成果
            if (deliverables.literature_review) {
                const lit = deliverables.literature_review;
                html += `
                    <div style="margin-bottom: 2rem;">
                        <h3 style="color: #28a745; margin-bottom: 1rem;">📚 文献综述成果</h3>
                        <div style="background: white; padding: 1.5rem; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 1rem; margin-bottom: 1rem;">
                                <div style="text-align: center;">
                                    <div style="font-size: 1.5rem; font-weight: bold; color: #28a745;">${lit.total_papers}</div>
                                    <div style="font-size: 0.9rem; color: #666;">文献总数</div>
                                </div>
                                <div style="text-align: center;">
                                    <div style="font-size: 1.5rem; font-weight: bold; color: #667eea;">${lit.average_quality}</div>
                                    <div style="font-size: 0.9rem; color: #666;">平均质量</div>
                                </div>
                                <div style="text-align: center;">
                                    <div style="font-size: 1.5rem; font-weight: bold; color: #ffc107;">${lit.average_relevance}</div>
                                    <div style="font-size: 0.9rem; color: #666;">平均相关性</div>
                                </div>
                                <div style="text-align: center;">
                                    <div style="font-size: 1.5rem; font-weight: bold; color: #dc3545;">${lit.total_citations}</div>
                                    <div style="font-size: 0.9rem; color: #666;">总引用数</div>
                                </div>
                            </div>
                            <h5 style="margin-bottom: 0.5rem;">交付物清单:</h5>
                            ${Object.entries(lit.deliverables).map(([key, value]) => `
                                <div style="padding: 0.5rem; background: #f8f9fa; border-radius: 4px; margin-bottom: 0.5rem;">
                                    <strong>${key}:</strong> ${value}
                                </div>
                            `).join('')}
                        </div>
                    </div>
                `;
            }
            
            // 实验设计成果
            if (deliverables.experiment_design) {
                const exp = deliverables.experiment_design;
                html += `
                    <div style="margin-bottom: 2rem;">
                        <h3 style="color: #ffc107; margin-bottom: 1rem;">⚗️ 实验设计成果</h3>
                        <div style="background: white; padding: 1.5rem; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                            <div style="margin-bottom: 1rem;">
                                <h5 style="margin-bottom: 0.5rem;">研究问题:</h5>
                                <p style="background: #f8f9fa; padding: 1rem; border-radius: 4px; margin: 0;">${exp.research_question}</p>
                            </div>
                            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; margin-bottom: 1rem;">
                                <div style="text-align: center;">
                                    <div style="font-size: 1.5rem; font-weight: bold; color: #ffc107;">${exp.experimental_groups_count}</div>
                                    <div style="font-size: 0.9rem; color: #666;">实验组</div>
                                </div>
                                <div style="text-align: center;">
                                    <div style="font-size: 1.5rem; font-weight: bold; color: #667eea;">${exp.evaluation_metrics_count}</div>
                                    <div style="font-size: 0.9rem; color: #666;">评估指标</div>
                                </div>
                                <div style="text-align: center;">
                                    <div style="font-size: 1.5rem; font-weight: bold; color: #28a745;">${exp.status}</div>
                                    <div style="font-size: 0.9rem; color: #666;">设计状态</div>
                                </div>
                            </div>
                            <h5 style="margin-bottom: 0.5rem;">交付物清单:</h5>
                            ${Object.entries(exp.deliverables).map(([key, value]) => `
                                <div style="padding: 0.5rem; background: #f8f9fa; border-radius: 4px; margin-bottom: 0.5rem;">
                                    <strong>${key}:</strong> ${value}
                                </div>
                            `).join('')}
                        </div>
                    </div>
                `;
            }
            
            // 数据分析配置成果
            if (deliverables.analysis_config) {
                const analysis = deliverables.analysis_config;
                html += `
                    <div style="margin-bottom: 2rem;">
                        <h3 style="color: #dc3545; margin-bottom: 1rem;">📊 数据分析成果</h3>
                        <div style="background: white; padding: 1.5rem; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; margin-bottom: 1rem;">
                                <div style="text-align: center;">
                                    <div style="font-size: 1.5rem; font-weight: bold; color: #dc3545;">${analysis.methods_count}</div>
                                    <div style="font-size: 0.9rem; color: #666;">分析方法</div>
                                </div>
                                <div style="text-align: center;">
                                    <div style="font-size: 1.5rem; font-weight: bold; color: #667eea;">${analysis.analysis_type}</div>
                                    <div style="font-size: 0.9rem; color: #666;">分析类型</div>
                                </div>
                                <div style="text-align: center;">
                                    <div style="font-size: 1.5rem; font-weight: bold; color: #28a745;">${analysis.status}</div>
                                    <div style="font-size: 0.9rem; color: #666;">配置状态</div>
                                </div>
                            </div>
                            <h5 style="margin-bottom: 0.5rem;">交付物清单:</h5>
                            ${Object.entries(analysis.deliverables).map(([key, value]) => `
                                <div style="padding: 0.5rem; background: #f8f9fa; border-radius: 4px; margin-bottom: 0.5rem;">
                                    <strong>${key}:</strong> ${value}
                                </div>
                            `).join('')}
                        </div>
                    </div>
                `;
            }
            
            // 任务执行历史
            if (deliverables.task_history && deliverables.task_history.length > 0) {
                html += `
                    <div style="margin-bottom: 2rem;">
                        <h3 style="color: #6c757d; margin-bottom: 1rem;">📋 任务执行历史</h3>
                        <div style="background: white; padding: 1.5rem; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                            ${deliverables.task_history.slice(0, 10).map(task => `
                                <div style="display: flex; justify-content: space-between; align-items: center; padding: 0.75rem; border-bottom: 1px solid #eee;">
                                    <div>
                                        <strong>${task.task_name}</strong>
                                        <div style="font-size: 0.9rem; color: #666;">${task.execution_log || '无日志'}</div>
                                    </div>
                                    <div style="text-align: right;">
                                        <span style="padding: 2px 8px; border-radius: 12px; font-size: 0.8rem; ${
                                            task.status === 'completed' ? 'background: #d4edda; color: #155724;' :
                                            task.status === 'failed' ? 'background: #f8d7da; color: #721c24;' :
                                            'background: #fff3cd; color: #856404;'
                                        }">${task.status}</span>
                                        <div style="font-size: 0.8rem; color: #666; margin-top: 0.25rem;">
                                            ${task.completed_at ? new Date(task.completed_at).toLocaleString() : '进行中'}
                                        </div>
                                    </div>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                `;
            }
            
            // 如果没有任何成果
            if (!deliverables.research_plan && !deliverables.literature_review && !deliverables.experiment_design && !deliverables.analysis_config) {
                html += `
                    <div style="text-align: center; padding: 3rem; background: #f8f9fa; border-radius: 8px; border: 2px dashed #ddd;">
                        <div style="font-size: 3rem; margin-bottom: 1rem;">📝</div>
                        <h3 style="color: #666; margin-bottom: 1rem;">暂无项目成果</h3>
                        <p style="color: #888; margin-bottom: 2rem;">
                            该项目还没有生成任何成果。请先执行以下操作：
                        </p>
                        <div style="display: flex; gap: 1rem; justify-content: center; flex-wrap: wrap;">
                            <button class="btn btn-success" onclick="startResearchPlanWorkflow()" style="margin: 0;">
                                📅 生成研究计划
                            </button>
                            <button class="btn" onclick="startLiteratureSearchWorkflow()" style="margin: 0;">
                                📚 搜索文献
                            </button>
                            <button class="btn" onclick="startExperimentDesignWorkflow()" style="margin: 0;">
                                ⚗️ 设计实验
                            </button>
                        </div>
                    </div>
                `;
            }
            
            content.innerHTML = html;
        }
        
        // 导出成果报告（占位函数）
        function exportDeliverables() {
            addAIMessage('ai', '📄 成果报告导出功能正在开发中。<br><br>在真实的学术研究系统中，您可以导出：<br>• PDF格式的完整成果报告<br>• Word文档格式的研究计划<br>• Excel表格格式的文献清单<br>• 实验设计的详细文档');
        }
        
        // 辅助函数
        function getStatusText(status) {
            const statusMap = {
                'pending': '待开始',
                'active': '进行中',
                'completed': '已完成',
                'paused': '已暂停',
                'cancelled': '已取消'
            };
            return statusMap[status] || '未知状态';
        }
        
        function formatDate(dateString) {
            if (!dateString) return '未知时间';
            try {
                const date = new Date(dateString);
                return date.toLocaleDateString('zh-CN');
            } catch (error) {
                return '无效日期';
            }
        }
        
        function getPhaseIcon(status) {
            const iconMap = {
                'pending': '⏳',
                'active': '🔄',
                'completed': '✅',
                'paused': '⏸️',
                'cancelled': '❌'
            };
            return iconMap[status] || '⏳';
        }
        
        // 🤖 自动化研究流程执行器
        async function executeAutomatedResearchFlow(researchPlan) {
            try {
                // 显示自动化状态指示器
                showAutomationStatus();
                updateStepStatus('plan', 'completed', '✅', '已完成');
                
                showInfo('🚀 开始执行自动化研究流程...');
                
                // 步骤1: 智能文献搜索
                updateStepStatus('literature', 'running', '🔄', '执行中...');
                await executeAutomatedLiteratureSearch(researchPlan);
                updateStepStatus('literature', 'completed', '✅', '已完成');
                
                // 步骤2: 智能实验设计
                updateStepStatus('experiment', 'running', '🔄', '执行中...');
                await executeAutomatedExperimentDesign(researchPlan);
                updateStepStatus('experiment', 'completed', '✅', '已完成');
                
                // 步骤3: 准备数据分析框架
                updateStepStatus('analysis', 'running', '🔄', '执行中...');
                await executeAutomatedAnalysisPreparation(researchPlan);
                updateStepStatus('analysis', 'completed', '✅', '已完成');
                
                showSuccess('🎉 自动化研究流程执行完成！您可以查看各个标签页的结果');
                
            } catch (error) {
                console.error('自动化流程执行错误:', error);
                // 标记当前步骤为错误状态
                const runningStep = document.querySelector('.automation-step.running');
                if (runningStep) {
                    const stepName = runningStep.getAttribute('data-step');
                    updateStepStatus(stepName, 'error', '❌', '执行失败');
                }
                showError('自动化流程执行过程中出现错误，您可以手动执行剩余步骤');
            }
        }
        
        // 显示自动化状态指示器
        function showAutomationStatus() {
            const statusDiv = document.getElementById('automationStatus');
            if (statusDiv) {
                statusDiv.style.display = 'block';
            }
        }
        
        // 更新步骤状态
        function updateStepStatus(stepName, status, icon, statusText) {
            const step = document.querySelector(`[data-step="${stepName}"]`);
            if (step) {
                // 移除所有状态类
                step.classList.remove('running', 'completed', 'error');
                
                // 添加新状态类
                if (status !== 'pending') {
                    step.classList.add(status);
                }
                
                // 更新图标和状态文本
                const iconElement = step.querySelector('.step-icon');
                const statusElement = step.querySelector('.step-status');
                
                if (iconElement) iconElement.textContent = icon;
                if (statusElement) statusElement.textContent = statusText;
            }
        }
        
        // 🔍 智能文献搜索（基于研究计划自动提取关键词）
        async function executeAutomatedLiteratureSearch(researchPlan) {
            try {
                showInfo('🔍 正在基于研究计划智能搜索文献...');
                
                // 从研究计划中智能提取关键词
                const response = await fetch('/api/literature/smart-search', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ 
                        project_id: projectId,
                        research_plan: researchPlan,
                        auto_extract_keywords: true
                    })
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const data = await response.json();
                
                if (data.success) {
                    showSuccess(`✅ 智能文献搜索完成！找到 ${data.total_results} 篇相关文献`);
                    renderLiteratureResults(data);
                    
                    // 切换到文献研究标签页显示结果
                    switchToTab('literature');
                } else {
                    throw new Error(data.message || '智能文献搜索失败');
                }
            } catch (error) {
                console.error('智能文献搜索错误:', error);
                showError('智能文献搜索失败，您可以手动搜索文献');
            }
        }
        
        // ⚗️ 智能实验设计（基于研究计划和文献自动生成）
        async function executeAutomatedExperimentDesign(researchPlan) {
            try {
                showInfo('⚗️ 正在基于研究计划和文献智能生成实验设计...');
                
                const response = await fetch(`/api/projects/${projectId}/smart-experiment-design`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        research_plan: researchPlan,
                        use_literature_context: true
                    })
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const data = await response.json();
                
                if (data.success) {
                    showSuccess('✅ 智能实验设计生成完成！');
                    renderExperimentDesign(data.experiment_design);
                    
                    // 切换到实验设计标签页显示结果
                    switchToTab('experiment');
                } else {
                    throw new Error(data.message || '智能实验设计失败');
                }
            } catch (error) {
                console.error('智能实验设计错误:', error);
                showError('智能实验设计失败，您可以手动设计实验');
            }
        }
        
        // 📊 智能数据分析准备（预设分析框架和指标）
        async function executeAutomatedAnalysisPreparation(researchPlan) {
            try {
                showInfo('📊 正在准备智能数据分析框架...');
                
                const response = await fetch(`/api/projects/${projectId}/smart-analysis-preparation`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        research_plan: researchPlan
                    })
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const data = await response.json();
                
                if (data.success) {
                    showSuccess('✅ 数据分析框架准备完成！');
                    renderAnalysisPreparation(data.analysis_framework);
                    
                    // 切换到数据分析标签页显示结果
                    switchToTab('analysis');
                } else {
                    throw new Error(data.message || '数据分析框架准备失败');
                }
            } catch (error) {
                console.error('数据分析框架准备错误:', error);
                showError('数据分析框架准备失败，您可以手动配置分析参数');
            }
        }
        
        // 标签页切换辅助函数
        function switchToTab(tabName) {
            try {
                // 隐藏所有标签内容
                document.querySelectorAll('.tab-content').forEach(content => {
                    content.classList.remove('active');
                });
                
                // 移除所有标签的激活状态
                document.querySelectorAll('.tab').forEach(tab => {
                    tab.classList.remove('active');
                });
                
                // 显示选中的标签内容
                const targetTab = document.getElementById(tabName);
                if (targetTab) {
                    targetTab.classList.add('active');
                }
                
                // 激活对应的标签按钮
                const tabButton = document.querySelector(`[onclick*="${tabName}"]`);
                if (tabButton) {
                    tabButton.classList.add('active');
                }
            } catch (error) {
                console.error('切换标签页错误:', error);
            }
        }
        

        // 真实文献搜索（连接学术数据库）
        async function searchRealLiterature() {
            try {
                showInfo('🌐 正在连接学术数据库搜索文献，请稍候...');
                
                const response = await fetch('/api/literature/real-search', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ 
                        keywords: [], // 空关键词表示使用项目信息自动提取
                        project_id: projectId
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    if (data.total_results > 0) {
                        showSuccess(`🎉 真实文献搜索完成！从学术数据库找到 ${data.total_results} 篇论文`);
                        renderLiteratureResults(data);
                        
                        // 显示搜索元信息
                        if (data.search_metadata && data.search_metadata.is_real_search) {
                            const metaInfo = document.createElement('div');
                            metaInfo.style.cssText = 'margin-bottom: 1rem; padding: 0.5rem; background: #e8f5e8; border-radius: 4px; font-size: 0.9rem; color: #2e7d32; border-left: 3px solid #4caf50;';
                            metaInfo.innerHTML = `
                                🌐 <strong>真实搜索结果:</strong> 
                                搜索了 ${data.search_metadata.databases_searched.join(', ')} 数据库，
                                用时 ${data.search_metadata.search_time} 秒
                            `;
                            
                            const content = document.getElementById('literatureContent');
                            content.insertBefore(metaInfo, content.firstChild);
                        }
                    } else {
                        showWarning('未找到相关文献，请尝试调整搜索关键词');
                    }
                } else {
                    showError(`文献搜索失败: ${data.message}`);
                }
            } catch (error) {
                showError('网络错误，请检查网络连接后重试');
                console.error('真实文献搜索错误:', error);
            }
        }
        
        // 搜索文献（本地数据库）（手动功能）
        async function searchLiterature() {
            // 如果是通过聊天窗口调用，使用智能提取的关键词
            let keywords = null;
            if (projectData && projectData.research_area) {
                keywords = projectData.research_area + ', ' + (projectData.methodology || '');
                addAIMessage('ai', `🔍 基于项目信息自动提取关键词: ${keywords}`);
            } else {
                addAIMessage('ai', '❌ 无法获取项目信息，请手动输入关键词');
                return;
            }
            
            try {
                showInfo('正在搜索文献，请稍候...');
                
                const keywordList = keywords.split(',').map(k => k.trim());
                const response = await fetch('/api/literature/search', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ 
                        keywords: keywordList,
                        project_id: projectId
                    })
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const data = await response.json();
                
                if (data.success) {
                    showSuccess(`搜索完成！找到 ${data.total_results} 篇相关文献`);
                    renderLiteratureResults(data);
                    switchToTab('literature');
                } else {
                    showError(data.message || '文献搜索失败');
                }
            } catch (error) {
                console.error('文献搜索错误:', error);
                showError('文献搜索时出现错误，请稍后重试');
            }
        }
        
        // 生成实验设计（手动功能）
        async function generateExperimentDesign() {
            try {
                showInfo('正在生成实验设计，请稍候...');
                
                const response = await fetch(`/api/projects/${projectId}/experiment-design`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        research_question: '基于当前项目的研究问题'
                    })
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const data = await response.json();
                
                if (data.success) {
                    showSuccess('实验设计生成成功！');
                    renderExperimentDesign(data.experiment_design);
                    switchToTab('experiment');
                } else {
                    showError(data.message || '实验设计生成失败');
                }
            } catch (error) {
                console.error('生成实验设计错误:', error);
                showError('生成实验设计时出现错误，请稍后重试');
            }
        }
        
        // 分析数据（手动功能）
        async function analyzeData() {
            try {
                showInfo('正在分析数据，请稍候...');
                
                const response = await fetch(`/api/projects/${projectId}/data-analysis`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        analysis_type: 'comprehensive'
                    })
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const data = await response.json();
                
                if (data.success) {
                    showSuccess('数据分析配置生成成功！');
                    renderAnalysisConfig(data.analysis_config);
                    switchToTab('analysis');
                } else {
                    showError(data.message || '数据分析失败');
                }
            } catch (error) {
                console.error('数据分析错误:', error);
                showError('数据分析时出现错误，请稍后重试');
            }
        }
        
        // 🚀 一键执行全流程
        async function executeFullAutomation() {
            showAIAssistant();
            addAIMessage('ai', 
                '🚀 开始执行一键全流程！<br><br>' +
                '将自动执行以下步骤：<br>' +
                '1. 生成智能研究计划<br>' +
                '2. 基于计划搜索相关文献<br>' +
                '3. 生成智能实验设计<br>' +
                '4. 准备数据分析框架<br><br>' +
                '整个过程可能需要几分钟时间，请耐心等待...'
            );
            
            try {
                showInfo('🚀 开始执行一键全流程自动化...');
                showAutomationStatus();
                
                // 步骤1: 生成研究计划
                updateStepStatus('plan', 'running', '🔄', '执行中...');
                const planResponse = await fetch(`/api/projects/${projectId}/research-plan`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({})
                });
                
                if (!planResponse.ok) {
                    throw new Error('研究计划生成失败');
                }
                
                const planData = await planResponse.json();
                if (!planData.success) {
                    throw new Error(planData.message || '研究计划生成失败');
                }
                
                updateStepStatus('plan', 'completed', '✅', '已完成');
                renderResearchPlan(planData.research_plan);
                switchToTab('research-plan');
                
                // 等待1秒让用户看到进度
                await new Promise(resolve => setTimeout(resolve, 1000));
                
                // 步骤2: 智能文献搜索
                updateStepStatus('literature', 'running', '🔄', '执行中...');
                await executeAutomatedLiteratureSearch(planData.research_plan);
                updateStepStatus('literature', 'completed', '✅', '已完成');
                
                await new Promise(resolve => setTimeout(resolve, 1000));
                
                // 步骤3: 智能实验设计
                updateStepStatus('experiment', 'running', '🔄', '执行中...');
                await executeAutomatedExperimentDesign(planData.research_plan);
                updateStepStatus('experiment', 'completed', '✅', '已完成');
                
                await new Promise(resolve => setTimeout(resolve, 1000));
                
                // 步骤4: 数据分析准备
                updateStepStatus('analysis', 'running', '🔄', '执行中...');
                await executeAutomatedAnalysisPreparation(planData.research_plan);
                updateStepStatus('analysis', 'completed', '✅', '已完成');
                
                showSuccess('🎉 一键全流程自动化执行完成！\n\n您可以查看各个标签页的详细结果，所有研究组件都已准备就绪。');
                
            } catch (error) {
                console.error('一键全流程执行错误:', error);
                
                // 标记当前步骤为错误状态
                const runningStep = document.querySelector('.automation-step.running');
                if (runningStep) {
                    const stepName = runningStep.getAttribute('data-step');
                    updateStepStatus(stepName, 'error', '❌', '执行失败');
                }
                
                showError(`一键全流程执行失败: ${error.message}\n\n您可以手动执行剩余步骤。`);
            }
        }
        
        // 渲染文献搜索结果
        // 渲染文献搜索结果
        function renderLiteratureResults(data) {
            try {
                const content = document.getElementById('literatureContent');
                
                if (!data.papers || data.papers.length === 0) {
                    content.innerHTML = `
                        <div style="text-align: center; padding: 3rem; background: #f8f9fa; border-radius: 8px; border: 2px dashed #ddd;">
                            <div style="font-size: 3rem; margin-bottom: 1rem;">📚</div>
                            <h3 style="color: #666; margin-bottom: 1rem;">暂无文献数据</h3>
                            <p style="color: #888; margin-bottom: 2rem;">
                                该项目还没有文献数据。您可以：
                            </p>
                            <div style="display: flex; gap: 1rem; justify-content: center; flex-wrap: wrap;">
                                <button class="btn btn-success" onclick="addSampleLiterature()" style="margin: 0;">
                                    📝 添加示例文献
                                </button>
                                <button class="btn" onclick="searchLiterature()" style="margin: 0;">
                                    🔍 搜索文献
                                </button>
                            </div>
                        </div>
                    `;
                    return;
                }
                
                const papersHTML = data.papers.map(paper => `
                    <div class="literature-item">
                        <div class="literature-title">${paper.title || '未知标题'}</div>
                        <div class="literature-authors">
                            作者: ${Array.isArray(paper.authors) ? paper.authors.join(', ') : (paper.authors || '未知作者')}
                        </div>
                        <div class="literature-journal">
                            ${paper.journal || '未知期刊'} (${paper.year || '未知年份'})
                            ${paper.doi ? `| DOI: ${paper.doi}` : ''}
                        </div>
                        <div style="margin: 0.5rem 0;">
                            <span class="score-badge ${paper.quality_score >= 8 ? 'score-high' : ''}">
                                质量: ${(paper.quality_score || 0).toFixed(1)}/10
                            </span>
                            <span class="score-badge ${paper.relevance_score >= 8 ? 'score-high' : ''}">
                                相关性: ${(paper.relevance_score || 0).toFixed(1)}/10
                            </span>
                            <span class="score-badge">引用: ${paper.citation_count || 0}</span>
                        </div>
                        <p style="font-size: 0.9rem; color: #666; line-height: 1.4; margin-top: 0.5rem;">
                            ${paper.abstract || '无摘要'}
                        </p>
                        ${paper.keywords ? `
                            <div style="margin-top: 0.5rem;">
                                <strong>关键词:</strong> 
                                ${(
                                    Array.isArray(paper.keywords)
                                        ? paper.keywords
                                        : typeof paper.keywords === 'string'
                                            ? paper.keywords.split(',').map(k => k.trim())
                                            : []
                                ).map(kw => `<span style="background: #e9ecef; padding: 2px 6px; border-radius: 3px; font-size: 0.8rem; margin-right: 0.3rem;">${kw}</span>`).join('')}
                            </div>
                        ` : ''}
                    </div>
                `).join('');
                
                content.innerHTML = `
                    <div style="margin-bottom: 1rem;">
                        <h4>📚 文献列表 (${data.total_results || data.papers.length} 篇)</h4>
                        ${data.search_metadata ? `
                            <p style="color: #666; font-size: 0.9rem;">
                                搜索时间: ${data.search_metadata.search_time || 0}秒 | 
                                数据库: ${(data.search_metadata.databases_searched || []).join(', ')}
                            </p>
                        ` : ''}
                    </div>
                    ${papersHTML}
                `;
                
                console.log(`✅ 成功渲染 ${data.papers.length} 篇文献`);
                
            } catch (error) {
                console.error('渲染文献结果时出现错误:', error);
                const content = document.getElementById('literatureContent');
                if (content) {
                    content.innerHTML = `
                        <div style="color: red; padding: 1rem; background: #f8d7da; border-radius: 5px;">
                            ❌ 文献数据渲染失败: ${error.message}
                        </div>
                    `;
                }
            }
        }
        
        // 渲染实验设计
        function renderExperimentDesign(design) {
            try {
                const content = document.getElementById('experimentContent');
                if (!content) return;
                
                if (!design) {
                    content.innerHTML = '<p style="color: #666;">实验设计数据格式错误</p>';
                    return;
                }
                
                content.innerHTML = `
                    <div style="margin-bottom: 2rem;">
                        <h4>🔬 研究问题</h4>
                        <p style="background: #f8f9fa; padding: 1rem; border-radius: 8px;">${design.research_question || '未定义研究问题'}</p>
                    </div>
                    
                    <div style="margin-bottom: 2rem;">
                        <h4>💡 研究假设</h4>
                        <ul>
                            ${(design.hypotheses || []).map(hypothesis => `<li>${hypothesis}</li>`).join('')}
                        </ul>
                    </div>
                    
                    <div style="margin-bottom: 2rem;">
                        <h4>🧪 实验组设计</h4>
                        ${(design.experimental_groups || []).map(group => `
                            <div style="border: 1px solid #eee; border-radius: 8px; padding: 1rem; margin-bottom: 1rem;">
                                <h5 style="color: #667eea;">${group.name || '未命名实验组'}</h5>
                                <p style="color: #666; margin-bottom: 1rem;">${group.description || '无描述'}</p>
                                <div style="background: #f8f9fa; padding: 0.5rem; border-radius: 4px; font-size: 0.9rem;">
                                    ${Object.entries(group.parameters || {}).map(([key, value]) => `<strong>${key}:</strong> ${value}`).join(' | ')}
                                </div>
                            </div>
                        `).join('')}
                    </div>
                    
                    <div style="margin-bottom: 2rem;">
                        <h4>📊 评估指标</h4>
                        ${(design.evaluation_metrics || []).map(metric => `
                            <div style="display: flex; justify-content: space-between; align-items: center; padding: 0.5rem; background: #f8f9fa; border-radius: 4px; margin-bottom: 0.5rem;">
                                <div>
                                    <strong>${metric.name || '未命名指标'}</strong>
                                    <br><small style="color: #666;">${metric.description || '无描述'}</small>
                                </div>
                                <span style="background: #667eea; color: white; padding: 2px 8px; border-radius: 4px; font-size: 0.8rem;">
                                    ${metric.target || '未设定目标'}
                                </span>
                            </div>
                        `).join('')}
                    </div>
                `;
            } catch (error) {
                console.error('渲染实验设计错误:', error);
                const content = document.getElementById('experimentContent');
                if (content) {
                    content.innerHTML = '<p style="color: #dc3545;">渲染实验设计时出现错误</p>';
                }
            }
        }
        
        // 渲染实验设计
        function renderExperimentDesign(design) {
            try {
                const content = document.getElementById('experimentContent');
                if (!content) {
                    console.error('找不到实验设计内容容器');
                    return;
                }
                
                if (!design || !design.research_question) {
                    content.innerHTML = `
                        <div style="text-align: center; padding: 3rem; background: #f8f9fa; border-radius: 8px; border: 2px dashed #ddd;">
                            <div style="font-size: 3rem; margin-bottom: 1rem;">⚗️</div>
                            <h3 style="color: #666; margin-bottom: 1rem;">暂无实验设计</h3>
                            <p style="color: #888; margin-bottom: 2rem;">
                                点击"智能实验设计"来创建实验方案
                            </p>
                            <button class="btn btn-success" onclick="generateExperimentDesign()">
                                ⚗️ 智能实验设计
                            </button>
                        </div>
                    `;
                    return;
                }
                
                // 生成研究假设HTML
                const hypothesesHTML = (design.hypotheses && design.hypotheses.length > 0) ? `
                    <div style="margin-bottom: 2rem;">
                        <h4 style="color: #28a745; margin-bottom: 1rem;">💡 研究假设</h4>
                        <ul style="background: white; padding: 1.5rem; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                            ${design.hypotheses.map(hypothesis => `<li style="margin-bottom: 0.5rem; line-height: 1.5;">${hypothesis}</li>`).join('')}
                        </ul>
                    </div>
                ` : '';
                
                // 生成实验组HTML
                const experimentalGroupsHTML = (design.experimental_groups && design.experimental_groups.length > 0) ? `
                    <div style="margin-bottom: 2rem;">
                        <h4 style="color: #ffc107; margin-bottom: 1rem;">🧪 实验组设计 (${design.experimental_groups.length}个)</h4>
                        <div style="background: white; padding: 1.5rem; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                            ${design.experimental_groups.map((group, index) => `
                                <div style="border: 1px solid #eee; border-radius: 8px; padding: 1.5rem; margin-bottom: 1rem; ${index === design.experimental_groups.length - 1 ? 'margin-bottom: 0;' : ''}">
                                    <h5 style="color: #667eea; margin-bottom: 1rem; display: flex; align-items: center;">
                                        <span style="background: #667eea; color: white; width: 24px; height: 24px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 0.8rem; margin-right: 0.5rem;">${index + 1}</span>
                                        ${group.name || `实验组 ${index + 1}`}
                                    </h5>
                                    <p style="color: #666; margin-bottom: 1rem; line-height: 1.5;">${group.description || '无描述'}</p>
                                    ${group.parameters && Object.keys(group.parameters).length > 0 ? `
                                        <div style="background: #f8f9fa; padding: 1rem; border-radius: 4px;">
                                            <strong style="color: #333; margin-bottom: 0.5rem; display: block;">参数配置:</strong>
                                            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 0.5rem; font-size: 0.9rem;">
                                                ${Object.entries(group.parameters).map(([key, value]) => `
                                                    <div><strong>${key}:</strong> ${value}</div>
                                                `).join('')}
                                            </div>
                                        </div>
                                    ` : ''}
                                </div>
                            `).join('')}
                        </div>
                    </div>
                ` : '';
                
                // 生成评估指标HTML
                const evaluationMetricsHTML = (design.evaluation_metrics && design.evaluation_metrics.length > 0) ? `
                    <div style="margin-bottom: 2rem;">
                        <h4 style="color: #dc3545; margin-bottom: 1rem;">📊 评估指标 (${design.evaluation_metrics.length}个)</h4>
                        <div style="background: white; padding: 1.5rem; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                            ${design.evaluation_metrics.map(metric => `
                                <div style="display: flex; justify-content: space-between; align-items: center; padding: 1rem; background: #f8f9fa; border-radius: 8px; margin-bottom: 1rem; border-left: 4px solid #dc3545;">
                                    <div style="flex: 1;">
                                        <div style="font-weight: bold; color: #333; margin-bottom: 0.5rem;">${metric.name || '未命名指标'}</div>
                                        <div style="color: #666; font-size: 0.9rem; line-height: 1.4;">${metric.description || '无描述'}</div>
                                    </div>
                                    ${metric.target ? `
                                        <div style="margin-left: 1rem;">
                                            <span style="background: #dc3545; color: white; padding: 4px 12px; border-radius: 20px; font-size: 0.8rem; font-weight: bold;">
                                                目标: ${metric.target}
                                            </span>
                                        </div>
                                    ` : ''}
                                </div>
                            `).join('')}
                        </div>
                    </div>
                ` : '';
                
                // 生成方法论HTML
                const methodologyHTML = design.methodology ? `
                    <div style="margin-bottom: 2rem;">
                        <h4 style="color: #6c757d; margin-bottom: 1rem;">🔬 实验方法</h4>
                        <div style="background: white; padding: 1.5rem; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                            <p style="margin: 0; line-height: 1.6; color: #333;">${design.methodology}</p>
                        </div>
                    </div>
                ` : '';
                
                // 渲染完整的实验设计
                content.innerHTML = `
                    <div style="margin-bottom: 2rem;">
                        <div style="background: #e3f2fd; padding: 1rem; border-radius: 8px; border-left: 4px solid #2196f3;">
                            <h4 style="margin: 0 0 0.5rem 0; color: #1976d2;">⚗️ 实验设计方案</h4>
                            <p style="margin: 0; color: #666;">
                                状态: ${design.status === 'draft' ? '草稿' : design.status === 'active' ? '进行中' : design.status === 'completed' ? '已完成' : '未知'} | 
                                设计ID: ${design.id || '未知'}
                            </p>
                        </div>
                    </div>
                    
                    <div style="margin-bottom: 2rem;">
                        <h4 style="color: #667eea; margin-bottom: 1rem;">🔬 研究问题</h4>
                        <div style="background: white; padding: 1.5rem; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                            <p style="margin: 0; font-size: 1.1rem; line-height: 1.6; color: #333; font-weight: 500;">${design.research_question}</p>
                        </div>
                    </div>
                    
                    ${hypothesesHTML}
                    ${experimentalGroupsHTML}
                    ${evaluationMetricsHTML}
                    ${methodologyHTML}
                    
                    <div style="margin-top: 2rem; padding: 1rem; background: #e8f5e8; border-radius: 8px; border-left: 4px solid #4caf50;">
                        <h5 style="margin: 0 0 0.5rem 0; color: #2e7d32;">💡 下一步建议</h5>
                        <p style="margin: 0; color: #666; font-size: 0.9rem;">
                            实验设计已完成。您可以开始准备实验数据，配置实验环境，或者继续进行数据分析准备工作。
                        </p>
                    </div>
                `;
                
                console.log('✅ 实验设计渲染成功');
                
            } catch (error) {
                console.error('渲染实验设计错误:', error);
                const content = document.getElementById('experimentContent');
                if (content) {
                    content.innerHTML = `
                        <div style="color: red; padding: 1rem; background: #f8d7da; border-radius: 5px;">
                            ❌ 实验设计渲染失败: ${error.message}
                        </div>
                    `;
                }
            }
        }
        
        // 渲染数据分析准备结果
        function renderAnalysisPreparation(framework) {
            try {
                const content = document.getElementById('analysisContent');
                if (!content) return;
                
                if (!framework) {
                    content.innerHTML = '<p style="color: #666;">分析框架数据格式错误</p>';
                    return;
                }
                
                content.innerHTML = `
                    <div style="margin-bottom: 2rem;">
                        <h4>📊 分析框架概览</h4>
                        <div style="background: #f8f9fa; padding: 1rem; border-radius: 8px;">
                            <p><strong>分析类型:</strong> ${framework.analysis_type || '综合分析'}</p>
                            <p><strong>数据类型:</strong> ${framework.data_type || '待确定'}</p>
                            <p><strong>预期样本量:</strong> ${framework.expected_sample_size || '待确定'}</p>
                        </div>
                    </div>
                    
                    <div style="margin-bottom: 2rem;">
                        <h4>🔧 推荐分析方法</h4>
                        ${(framework.recommended_methods || []).map(method => `
                            <div style="border: 1px solid #eee; border-radius: 8px; padding: 1rem; margin-bottom: 1rem;">
                                <h5 style="color: #667eea;">${method.name || '未命名方法'}</h5>
                                <p style="color: #666; margin-bottom: 0.5rem;">${method.description || '无描述'}</p>
                                <div style="font-size: 0.9rem;">
                                    <strong>适用场景:</strong> ${method.use_case || '通用'}
                                </div>
                            </div>
                        `).join('')}
                    </div>
                    
                    <div style="margin-bottom: 2rem;">
                        <h4>📈 关键指标</h4>
                        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem;">
                            ${(framework.key_metrics || []).map(metric => `
                                <div style="background: #f8f9fa; padding: 1rem; border-radius: 8px; text-align: center;">
                                    <div style="font-size: 1.2rem; font-weight: bold; color: #667eea;">${metric.name || '未命名指标'}</div>
                                    <div style="font-size: 0.9rem; color: #666; margin-top: 0.5rem;">${metric.description || '无描述'}</div>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                    
                    <div style="margin-bottom: 2rem;">
                        <h4>⚙️ 分析配置</h4>
                        <div style="background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 1rem;">
                            <p style="margin: 0;"><strong>📝 注意:</strong> 分析框架已准备就绪，您可以上传数据开始分析，或根据实际需求调整配置参数。</p>
                        </div>
                    </div>
                `;
            } catch (error) {
                console.error('渲染分析准备结果错误:', error);
                const content = document.getElementById('analysisContent');
                if (content) {
                    content.innerHTML = '<p style="color: #dc3545;">渲染分析准备结果时出现错误</p>';
                }
            }
        }
        
        // 渲染数据分析配置
        function renderAnalysisConfig(config) {
            try {
                const content = document.getElementById('analysisContent');
                if (!content) return;
                
                if (!config) {
                    content.innerHTML = '<p style="color: #666;">数据分析配置数据格式错误</p>';
                    return;
                }
                
                // 生成数据源HTML
                const dataSourcesHTML = (config.data_sources || []).map(source => `
                    <div style="background: #f8f9fa; padding: 1rem; border-radius: 8px; margin-bottom: 1rem;">
                        <h5 style="margin: 0 0 0.5rem 0; color: #333;">${source.name}</h5>
                        <p style="margin: 0 0 0.5rem 0; color: #666; font-size: 0.9rem;">${source.description}</p>
                        <div style="font-size: 0.8rem; color: #888;">
                            <span>格式: ${source.format}</span> | 
                            <span>大小: ${source.size}</span> | 
                            <span>类型: ${source.type}</span>
                        </div>
                    </div>
                `).join('');
                
                // 生成分析方法HTML
                const methodsHTML = (config.analysis_methods || []).map(method => `
                    <div style="background: #e3f2fd; padding: 1rem; border-radius: 8px; margin-bottom: 1rem;">
                        <h5 style="margin: 0 0 0.5rem 0; color: #1976d2;">${method.name}</h5>
                        <p style="margin: 0 0 0.5rem 0; color: #666; font-size: 0.9rem;">${method.description}</p>
                        <div style="font-size: 0.8rem; color: #1976d2;">
                            <strong>工具:</strong> ${(method.tools || []).join(', ')}
                        </div>
                        <div style="font-size: 0.8rem; color: #666; margin-top: 0.3rem;">
                            <strong>输出:</strong> ${method.output}
                        </div>
                    </div>
                `).join('');
                
                // 生成统计检验HTML
                const testsHTML = (config.statistical_tests || []).map(test => `
                    <div style="background: #fff3e0; padding: 1rem; border-radius: 8px; margin-bottom: 1rem;">
                        <h5 style="margin: 0 0 0.5rem 0; color: #f57c00;">${test.name}</h5>
                        <p style="margin: 0 0 0.5rem 0; color: #666; font-size: 0.9rem;">${test.purpose}</p>
                        <div style="font-size: 0.8rem; color: #f57c00;">
                            <strong>适用条件:</strong> ${test.condition}
                        </div>
                        <div style="font-size: 0.8rem; color: #666; margin-top: 0.3rem;">
                            <strong>显著性水平:</strong> α = ${test.significance_level}
                        </div>
                    </div>
                `).join('');
                
                // 生成可视化类型HTML
                const visualizationsHTML = (config.visualization_types || []).map(viz => `
                    <div style="background: #e8f5e8; padding: 1rem; border-radius: 8px; margin-bottom: 1rem;">
                        <h5 style="margin: 0 0 0.5rem 0; color: #2e7d32;">${viz.name}</h5>
                        <p style="margin: 0 0 0.5rem 0; color: #666; font-size: 0.9rem;">${viz.purpose}</p>
                        <div style="font-size: 0.8rem; color: #2e7d32;">
                            <strong>工具:</strong> ${viz.tool} | 
                            <strong>应用场景:</strong> ${viz.use_case}
                        </div>
                    </div>
                `).join('');
                
                content.innerHTML = `
                    <div style="margin-bottom: 2rem;">
                        <h4>📊 数据分析配置</h4>
                        <div style="background: #e3f2fd; padding: 1rem; border-radius: 8px; border-left: 4px solid #2196f3; margin-bottom: 1rem;">
                            <strong>分析类型:</strong> ${config.analysis_type || '统计分析'} | 
                            <strong>配置ID:</strong> ${config.id || 'Unknown'} | 
                            <strong>状态:</strong> ${config.status || 'configured'}
                        </div>
                    </div>
                    
                    <div style="margin-bottom: 2rem;">
                        <h4>📁 数据源配置 (${(config.data_sources || []).length}个)</h4>
                        ${dataSourcesHTML || '<p style="color: #666;">暂无数据源配置</p>'}
                    </div>
                    
                    <div style="margin-bottom: 2rem;">
                        <h4>🔬 分析方法 (${(config.analysis_methods || []).length}个)</h4>
                        ${methodsHTML || '<p style="color: #666;">暂无分析方法</p>'}
                    </div>
                    
                    <div style="margin-bottom: 2rem;">
                        <h4>📈 统计检验 (${(config.statistical_tests || []).length}个)</h4>
                        ${testsHTML || '<p style="color: #666;">暂无统计检验</p>'}
                    </div>
                    
                    <div style="margin-bottom: 2rem;">
                        <h4>📊 可视化方案 (${(config.visualization_types || []).length}个)</h4>
                        ${visualizationsHTML || '<p style="color: #666;">暂无可视化方案</p>'}
                    </div>
                    
                    ${config.expected_results ? `
                        <div style="margin-bottom: 2rem;">
                            <h4>🎯 预期结果</h4>
                            <div style="background: #f8f9fa; padding: 1rem; border-radius: 8px; white-space: pre-line;">
                                ${config.expected_results}
                            </div>
                        </div>
                    ` : ''}
                `;
                
                console.log('✅ 数据分析配置渲染成功');
                
            } catch (error) {
                console.error('渲染数据分析配置错误:', error);
                const content = document.getElementById('analysisContent');
                if (content) {
                    content.innerHTML = `
                        <div style="color: red; padding: 1rem; background: #f8d7da; border-radius: 5px;">
                            ❌ 数据分析配置渲染失败: ${error.message}
                        </div>
                    `;
                }
            }
        }
        
        // 渲染数据分析结果（原有功能）
        function renderAnalysisResults(results) {
            try {
                const content = document.getElementById('analysisContent');
                if (!content) return;
                
                if (!results) {
                    content.innerHTML = '<p style="color: #666;">分析结果数据格式错误</p>';
                    return;
                }
                
                content.innerHTML = `
                    <div style="margin-bottom: 2rem;">
                        <h4>📊 数据概览</h4>
                        <div class="stats-grid" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 1rem;">
                            <div class="stat-item" style="background: #f8f9fa; padding: 1rem; border-radius: 8px; text-align: center;">
                                <div class="stat-number" style="font-size: 1.5rem; font-weight: bold; color: #667eea;">${(results.data_summary?.total_samples || 0).toLocaleString()}</div>
                                <div class="stat-label" style="font-size: 0.9rem; color: #666;">样本数量</div>
                            </div>
                            <div class="stat-item" style="background: #f8f9fa; padding: 1rem; border-radius: 8px; text-align: center;">
                                <div class="stat-number" style="font-size: 1.5rem; font-weight: bold; color: #667eea;">${results.data_summary?.features || 0}</div>
                                <div class="stat-label" style="font-size: 0.9rem; color: #666;">特征数量</div>
                            </div>
                        </div>
                    </div>
                    
                    <div style="margin-bottom: 2rem;">
                        <h4>📈 分析结果</h4>
                        <p style="background: #f8f9fa; padding: 1rem; border-radius: 8px;">
                            数据分析功能正在开发中，请稍后查看详细结果。
                        </p>
                    </div>
                `;
            } catch (error) {
                console.error('渲染分析结果错误:', error);
                const content = document.getElementById('analysisContent');
                if (content) {
                    content.innerHTML = '<p style="color: #dc3545;">渲染分析结果时出现错误</p>';
                }
            }
        }   
 
        
        // 调试函数：检查项目数据
        function debugProjectData() {
            console.log('=== 项目数据调试信息 ===');
            console.log('项目ID:', projectId);
            console.log('项目数据:', projectData);
            
            if (projectData) {
                console.log('文献摘要:', projectData.literature_summary);
                console.log('研究计划:', projectData.research_plan);
            }
            
            // 检查DOM元素
            console.log('文献内容元素:', document.getElementById('literatureContent'));
            console.log('研究计划内容元素:', document.getElementById('researchPlanContent'));
        }
        
        // 调试函数：强制重新加载数据
        async function debugReloadData() {
            console.log('🔄 强制重新加载项目数据...');
            await loadProjectDetail();
            console.log('✅ 数据重新加载完成');
        }
        
        // 生成研究计划（主要功能）
        async function generateResearchPlan() {
            try {
                showInfo('🤖 正在生成研究计划，请稍候...');
                hideProgress();
                showProgress('正在生成研究计划...', 20);
                
                const response = await fetch(`/api/projects/${projectId}/research-plan`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({})
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const data = await response.json();
                
                if (data.success) {
                    hideProgress();
                    
                    // 保存研究计划到全局变量
                    currentResearchPlan = data.research_plan;
                    
                    // 渲染研究计划
                    renderResearchPlan(data.research_plan);
                    
                    // 显示成功消息
                    if (data.is_existing) {
                        showSuccess(`✅ 加载已有研究计划成功！包含 ${data.research_plan.phases.length} 个研究阶段`);
                    } else {
                        showSuccess(`✅ 研究计划生成成功！包含 ${data.research_plan.phases.length} 个研究阶段`);
                        
                        // 询问是否继续执行自动化流程
                        setTimeout(() => {
                            addAIMessage('ai', 
                                '🎉 研究计划已生成完成！<br><br>' +
                                '您现在可以：<br>' +
                                '1. 查看详细的研究计划内容<br>' +
                                '2. 继续执行自动化研究流程（文献搜索、实验设计等）<br>' +
                                '3. 手动执行各个研究步骤<br><br>' +
                                '是否要继续执行自动化研究流程？回复"继续"或"手动"'
                            );
                            
                            // 设置工作流程状态
                            currentWorkflow = {
                                type: 'research_plan_continue',
                                data: data.research_plan
                            };
                        }, 1000);
                    }
                    
                    // 切换到研究计划标签页
                    switchToTab('research-plan');
                    
                } else {
                    hideProgress();
                    showError(`研究计划生成失败: ${data.message}`);
                }
                
            } catch (error) {
                hideProgress();
                console.error('生成研究计划错误:', error);
                showError(`生成研究计划时出现错误: ${error.message}`);
            }
        }
        
        // 渲染研究计划
        function renderResearchPlan(plan) {
            try {
                const content = document.getElementById('researchPlanContent');
                if (!content) {
                    console.error('找不到研究计划内容容器');
                    return;
                }
                
                if (!plan || !plan.phases) {
                    content.innerHTML = `
                        <div style="text-align: center; padding: 3rem; background: #f8f9fa; border-radius: 8px; border: 2px dashed #ddd;">
                            <div style="font-size: 3rem; margin-bottom: 1rem;">📅</div>
                            <h3 style="color: #666; margin-bottom: 1rem;">暂无研究计划</h3>
                            <p style="color: #888; margin-bottom: 2rem;">
                                点击"智能生成研究计划"来创建详细的研究计划
                            </p>
                            <button class="btn btn-success" onclick="generateResearchPlan()">
                                🤖 智能生成研究计划
                            </button>
                        </div>
                    `;
                    return;
                }
                
                // 生成阶段HTML
                const phasesHTML = plan.phases.map((phase, index) => {
                    const statusClass = phase.status === 'completed' ? 'completed' : 
                                       phase.status === 'ready' || phase.status === 'active' ? 'in-progress' : 'pending';
                    const statusIcon = phase.status === 'completed' ? '✅' : 
                                      phase.status === 'ready' || phase.status === 'active' ? '🔄' : '⏳';
                    
                    return `
                        <div class="phase-item ${statusClass}" style="display: flex; align-items: flex-start; padding: 1.5rem; margin-bottom: 1.5rem; background: #f8f9fa; border-radius: 8px; border-left: 4px solid ${statusClass === 'completed' ? '#28a745' : statusClass === 'in-progress' ? '#ffc107' : '#6c757d'};">
                            <div class="phase-icon" style="font-size: 2rem; margin-right: 1rem; flex-shrink: 0;">
                                ${statusIcon}
                            </div>
                            <div class="phase-content" style="flex: 1;">
                                <div class="phase-name" style="font-size: 1.2rem; font-weight: bold; margin-bottom: 0.5rem; color: #333;">
                                    阶段 ${index + 1}: ${phase.name}
                                </div>
                                <div class="phase-description" style="color: #666; margin-bottom: 1rem; line-height: 1.5;">
                                    ${phase.description}
                                </div>
                                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 1rem; margin-bottom: 1rem;">
                                    <div>
                                        <strong style="color: #667eea;">⏱️ 预计时长:</strong>
                                        <div style="margin-top: 0.3rem; color: #666;">${phase.duration}</div>
                                    </div>
                                    <div>
                                        <strong style="color: #28a745;">📋 状态:</strong>
                                        <div style="margin-top: 0.3rem;">
                                            <span style="padding: 2px 8px; border-radius: 12px; font-size: 0.8rem; ${
                                                phase.status === 'completed' ? 'background: #d4edda; color: #155724;' :
                                                phase.status === 'ready' || phase.status === 'active' ? 'background: #fff3cd; color: #856404;' :
                                                'background: #e9ecef; color: #495057;'
                                            }">
                                                ${phase.status === 'completed' ? '已完成' : 
                                                  phase.status === 'ready' ? '准备就绪' :
                                                  phase.status === 'active' ? '进行中' : '待开始'}
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                
                                ${phase.deliverables && phase.deliverables.length > 0 ? `
                                    <div style="margin-bottom: 1rem;">
                                        <strong style="color: #dc3545;">📦 交付物:</strong>
                                        <ul style="margin: 0.5rem 0 0 1.5rem; color: #666;">
                                            ${phase.deliverables.map(deliverable => `<li>${deliverable}</li>`).join('')}
                                        </ul>
                                    </div>
                                ` : ''}
                                
                                ${phase.tasks && phase.tasks.length > 0 ? `
                                    <div style="margin-bottom: 1rem;">
                                        <strong style="color: #ffc107;">✅ 主要任务:</strong>
                                        <ul style="margin: 0.5rem 0 0 1.5rem; color: #666;">
                                            ${phase.tasks.map(task => `<li>${task}</li>`).join('')}
                                        </ul>
                                    </div>
                                ` : ''}
                                
                                ${phase.resources_needed && phase.resources_needed.length > 0 ? `
                                    <div>
                                        <strong style="color: #6c757d;">🛠️ 所需资源:</strong>
                                        <ul style="margin: 0.5rem 0 0 1.5rem; color: #666;">
                                            ${phase.resources_needed.map(resource => `<li>${resource}</li>`).join('')}
                                        </ul>
                                    </div>
                                ` : ''}
                            </div>
                        </div>
                    `;
                }).join('');
                
                // 生成时间线HTML
                const timelineHTML = plan.timeline && plan.timeline.milestones ? `
                    <div style="margin-bottom: 2rem;">
                        <h4 style="color: #667eea; margin-bottom: 1rem;">📅 项目时间线</h4>
                        <div style="background: white; padding: 1.5rem; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                            <div style="margin-bottom: 1rem;">
                                <strong>总体时长:</strong> ${plan.total_duration || '待确定'} | 
                                <strong>开始日期:</strong> ${plan.timeline.start_date || '待确定'} | 
                                <strong>预计结束:</strong> ${plan.timeline.estimated_end_date || '待确定'}
                            </div>
                            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem;">
                                ${plan.timeline.milestones.map(milestone => `
                                    <div style="background: #f8f9fa; padding: 1rem; border-radius: 8px; text-align: center;">
                                        <div style="font-size: 1.2rem; font-weight: bold; color: #667eea;">第${milestone.week}周</div>
                                        <div style="font-size: 0.9rem; color: #666; margin-top: 0.5rem;">${milestone.name}</div>
                                    </div>
                                `).join('')}
                            </div>
                        </div>
                    </div>
                ` : '';
                
                // 生成风险评估HTML
                const riskAssessmentHTML = plan.risk_assessment && plan.risk_assessment.length > 0 ? `
                    <div style="margin-bottom: 2rem;">
                        <h4 style="color: #dc3545; margin-bottom: 1rem;">⚠️ 风险评估</h4>
                        <div style="background: white; padding: 1.5rem; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                            ${plan.risk_assessment.map(risk => `
                                <div style="border: 1px solid #eee; border-radius: 8px; padding: 1rem; margin-bottom: 1rem;">
                                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem;">
                                        <strong style="color: #dc3545;">${risk.risk}</strong>
                                        <div>
                                            <span style="padding: 2px 8px; border-radius: 12px; font-size: 0.8rem; background: #fff3cd; color: #856404; margin-right: 0.5rem;">
                                                概率: ${risk.probability}
                                            </span>
                                            <span style="padding: 2px 8px; border-radius: 12px; font-size: 0.8rem; background: #f8d7da; color: #721c24;">
                                                影响: ${risk.impact}
                                            </span>
                                        </div>
                                    </div>
                                    <div style="color: #666; font-size: 0.9rem;">
                                        <strong>缓解措施:</strong> ${risk.mitigation}
                                    </div>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                ` : '';
                
                // 渲染完整的研究计划
                content.innerHTML = `
                    <div style="margin-bottom: 2rem;">
                        <div style="background: #e3f2fd; padding: 1rem; border-radius: 8px; border-left: 4px solid #2196f3;">
                            <h4 style="margin: 0 0 0.5rem 0; color: #1976d2;">📋 ${plan.title || '研究计划'}</h4>
                            <p style="margin: 0; color: #666;">
                                生成时间: ${plan.generated_at ? new Date(plan.generated_at).toLocaleString() : '未知'} | 
                                总时长: ${plan.total_duration || '待确定'} | 
                                阶段数: ${plan.phases.length}个
                            </p>
                        </div>
                    </div>
                    
                    ${timelineHTML}
                    
                    <div style="margin-bottom: 2rem;">
                        <h4 style="color: #28a745; margin-bottom: 1rem;">🔬 研究阶段详情</h4>
                        ${phasesHTML}
                    </div>
                    
                    ${riskAssessmentHTML}
                    
                    <div style="margin-top: 2rem; padding: 1rem; background: #e8f5e8; border-radius: 8px; border-left: 4px solid #4caf50;">
                        <h5 style="margin: 0 0 0.5rem 0; color: #2e7d32;">💡 下一步建议</h5>
                        <p style="margin: 0; color: #666; font-size: 0.9rem;">
                            研究计划已生成完成。您可以点击侧边栏的"一键执行全流程"按钮来自动执行文献搜索、实验设计和数据分析准备，
                            或者手动执行各个研究步骤。
                        </p>
                    </div>
                `;
                
                // 更新侧边栏的研究进度
                updateResearchProgress(plan.phases);
                
                console.log('✅ 研究计划渲染成功');
                
            } catch (error) {
                console.error('渲染研究计划错误:', error);
                const content = document.getElementById('researchPlanContent');
                if (content) {
                    content.innerHTML = `
                        <div style="color: red; padding: 1rem; background: #f8d7da; border-radius: 5px;">
                            ❌ 研究计划渲染失败: ${error.message}
                        </div>
                    `;
                }
            }
        }
        
        // 更新研究进度显示
        function updateResearchProgress(phases) {
            try {
                const phaseList = document.getElementById('phaseList');
                if (!phaseList || !phases) return;
                
                const phasesHTML = phases.map((phase, index) => {
                    const statusClass = phase.status === 'completed' ? 'completed' : 
                                       phase.status === 'ready' || phase.status === 'active' ? 'in-progress' : 'pending';
                    const statusIcon = phase.status === 'completed' ? '✅' : 
                                      phase.status === 'ready' || phase.status === 'active' ? '🔄' : '⏳';
                    const progressText = phase.progress ? `${phase.progress}%` : '0%';
                    
                    return `
                        <li class="phase-item ${statusClass}">
                            <div class="phase-icon">${statusIcon}</div>
                            <div class="phase-content">
                                <div class="phase-name">${phase.name}</div>
                                <div class="phase-progress">进度: ${progressText}</div>
                            </div>
                        </li>
                    `;
                }).join('');
                
                phaseList.innerHTML = phasesHTML;
                
            } catch (error) {
                console.error('更新研究进度错误:', error);
            }
        }

        // 生成研究报告
        async function generateReport() {
            try {
                showInfo('📄 正在生成研究报告，请稍候...');
                showProgress('正在收集项目数据...', 10);
                
                const response = await fetch(`/api/projects/${projectId}/generate-report`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        report_type: 'comprehensive'
                    })
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                updateProgress('正在生成报告内容...', 50);
                
                const data = await response.json();
                
                if (data.success) {
                    updateProgress('正在渲染报告...', 80);
                    
                    // 渲染报告
                    renderReport(data.report, data.statistics);
                    
                    hideProgress();
                    showSuccess(`✅ 研究报告生成成功！包含 ${data.statistics.total_sections} 个章节`);
                    
                    // 显示报告统计信息
                    addAIMessage('ai', 
                        `📄 研究报告生成完成！<br><br>` +
                        `📊 报告统计：<br>` +
                        `• 章节数量: ${data.statistics.total_sections}<br>` +
                        `• 预估页数: ${data.statistics.total_pages_estimated}<br>` +
                        `• 预估字数: ${data.statistics.word_count_estimated}<br>` +
                        `• 完成度: ${data.statistics.completion_percentage}%<br><br>` +
                        `您可以在页面中查看完整报告，或导出为PDF文件。`
                    );
                    
                    // 创建新的报告标签页或在现有页面显示
                    showReportModal(data.report, data.statistics);
                    
                } else {
                    hideProgress();
                    showError(`研究报告生成失败: ${data.message}`);
                }
                
            } catch (error) {
                hideProgress();
                console.error('生成研究报告错误:', error);
                showError(`生成研究报告时出现错误: ${error.message}`);
            }
        }
        
        // 渲染报告内容
        function renderReport(report, statistics) {
            try {
                console.log('📄 开始渲染研究报告...');
                
                // 生成报告HTML
                let reportHTML = `
                    <div style="max-width: 800px; margin: 0 auto; background: white; padding: 2rem; font-family: 'Times New Roman', serif; line-height: 1.6;">
                        <!-- 报告标题页 -->
                        <div style="text-align: center; margin-bottom: 3rem; padding-bottom: 2rem; border-bottom: 2px solid #333;">
                            <h1 style="font-size: 2rem; margin-bottom: 1rem; color: #333;">${report.title}</h1>
                            <p style="font-size: 1.1rem; color: #666; margin-bottom: 0.5rem;">学术研究报告</p>
                            <p style="font-size: 1rem; color: #888;">生成时间: ${new Date(report.generated_at).toLocaleString()}</p>
                            <p style="font-size: 0.9rem; color: #999;">报告ID: ${report.id}</p>
                        </div>
                `;
                
                // 生成各个章节
                report.sections.forEach((section, index) => {
                    reportHTML += `
                        <div style="margin-bottom: 2rem; page-break-inside: avoid;">
                            <h2 style="font-size: 1.5rem; color: #333; margin-bottom: 1rem; border-bottom: 1px solid #ddd; padding-bottom: 0.5rem;">
                                ${index + 1}. ${section.title}
                            </h2>
                            <div style="margin-left: 1rem;">
                                ${renderReportSection(section)}
                            </div>
                        </div>
                    `;
                });
                
                // 添加报告统计信息
                reportHTML += `
                    <div style="margin-top: 3rem; padding-top: 2rem; border-top: 2px solid #333;">
                        <h3 style="color: #666; margin-bottom: 1rem;">📊 报告统计</h3>
                        <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 1rem; background: #f8f9fa; padding: 1rem; border-radius: 8px;">
                            <div><strong>章节数量:</strong> ${statistics.total_sections}</div>
                            <div><strong>预估页数:</strong> ${statistics.total_pages_estimated}</div>
                            <div><strong>预估字数:</strong> ${statistics.word_count_estimated}</div>
                            <div><strong>完成度:</strong> ${statistics.completion_percentage}%</div>
                        </div>
                    </div>
                `;
                
                reportHTML += `</div>`;
                
                // 存储报告HTML供后续使用
                window.currentReport = {
                    html: reportHTML,
                    data: report,
                    statistics: statistics
                };
                
                console.log('✅ 研究报告渲染成功');
                
            } catch (error) {
                console.error('渲染研究报告错误:', error);
                showError('研究报告渲染失败');
            }
        }
        
        // 渲染报告章节内容
        function renderReportSection(section) {
            let sectionHTML = '';
            
            if (!section.content) {
                return '<p style="color: #666; font-style: italic;">暂无内容</p>';
            }
            
            // 根据章节ID进行特定渲染
            switch (section.section_id) {
                case 'overview':
                    sectionHTML += renderOverviewSection(section.content);
                    break;
                case 'research_plan':
                    sectionHTML += renderResearchPlanSection(section.content);
                    break;
                case 'literature_review':
                    sectionHTML += renderLiteratureSection(section.content);
                    break;
                case 'experiment_design':
                    sectionHTML += renderExperimentSection(section.content);
                    break;
                case 'data_analysis':
                    sectionHTML += renderAnalysisSection(section.content);
                    break;
                case 'conclusion':
                    sectionHTML += renderConclusionSection(section.content);
                    break;
                default:
                    sectionHTML += renderGenericSection(section.content);
            }
            
            return sectionHTML;
        }
        
        // 渲染项目概述章节
        function renderOverviewSection(content) {
            return `
                <div style="margin-bottom: 1.5rem;">
                    <h4 style="color: #333; margin-bottom: 1rem;">项目基本信息</h4>
                    <table style="width: 100%; border-collapse: collapse; margin-bottom: 1rem;">
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 0.5rem; font-weight: bold; width: 120px;">项目标题:</td>
                            <td style="padding: 0.5rem;">${content.project_title || '未指定'}</td>
                        </tr>
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 0.5rem; font-weight: bold;">研究领域:</td>
                            <td style="padding: 0.5rem;">${content.research_area || '未指定'}</td>
                        </tr>
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 0.5rem; font-weight: bold;">研究方法:</td>
                            <td style="padding: 0.5rem;">${content.methodology || '未指定'}</td>
                        </tr>
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 0.5rem; font-weight: bold;">预期时长:</td>
                            <td style="padding: 0.5rem;">${content.timeline || '未指定'}</td>
                        </tr>
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 0.5rem; font-weight: bold;">项目状态:</td>
                            <td style="padding: 0.5rem;">${getStatusText(content.status)} (${content.progress || 0}%)</td>
                        </tr>
                    </table>
                </div>
                
                <div style="margin-bottom: 1.5rem;">
                    <h4 style="color: #333; margin-bottom: 1rem;">项目描述</h4>
                    <p style="line-height: 1.6; text-align: justify;">${content.description || '暂无描述'}</p>
                </div>
                
                ${content.objectives && content.objectives.length > 0 ? `
                    <div style="margin-bottom: 1.5rem;">
                        <h4 style="color: #333; margin-bottom: 1rem;">研究目标</h4>
                        <ol style="padding-left: 2rem;">
                            ${content.objectives.map(obj => `<li style="margin-bottom: 0.5rem; line-height: 1.5;">${obj}</li>`).join('')}
                        </ol>
                    </div>
                ` : ''}
            `;
        }
        
        // 渲染研究计划章节
        function renderResearchPlanSection(content) {
            return `
                <div style="margin-bottom: 1.5rem;">
                    <h4 style="color: #333; margin-bottom: 1rem;">计划概览</h4>
                    <p><strong>总体时长:</strong> ${content.total_duration || '未指定'}</p>
                    <p><strong>研究阶段:</strong> ${content.phases_count || 0} 个阶段</p>
                </div>
                
                ${content.phases && content.phases.length > 0 ? `
                    <div style="margin-bottom: 1.5rem;">
                        <h4 style="color: #333; margin-bottom: 1rem;">研究阶段详情</h4>
                        ${content.phases.map((phase, index) => `
                            <div style="border: 1px solid #ddd; border-radius: 8px; padding: 1rem; margin-bottom: 1rem;">
                                <h5 style="color: #667eea; margin-bottom: 0.5rem;">阶段 ${index + 1}: ${phase.name}</h5>
                                <p style="margin-bottom: 0.5rem; color: #666;">${phase.description}</p>
                                <p><strong>预计时长:</strong> ${phase.duration}</p>
                                <p><strong>状态:</strong> ${getStatusText(phase.status)}</p>
                                ${phase.deliverables && phase.deliverables.length > 0 ? `
                                    <div style="margin-top: 0.5rem;">
                                        <strong>主要交付物:</strong>
                                        <ul style="margin: 0.5rem 0; padding-left: 1.5rem;">
                                            ${phase.deliverables.map(d => `<li>${d}</li>`).join('')}
                                        </ul>
                                    </div>
                                ` : ''}
                            </div>
                        `).join('')}
                    </div>
                ` : ''}
                
                ${content.risk_assessment && content.risk_assessment.length > 0 ? `
                    <div style="margin-bottom: 1.5rem;">
                        <h4 style="color: #333; margin-bottom: 1rem;">风险评估</h4>
                        ${content.risk_assessment.map(risk => `
                            <div style="background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 1rem; margin-bottom: 0.5rem;">
                                <p><strong>风险:</strong> ${risk.risk}</p>
                                <p><strong>概率:</strong> ${risk.probability} | <strong>影响:</strong> ${risk.impact}</p>
                                <p><strong>缓解措施:</strong> ${risk.mitigation}</p>
                            </div>
                        `).join('')}
                    </div>
                ` : ''}
            `;
        }
        
        // 渲染文献综述章节
        function renderLiteratureSection(content) {
            return `
                <div style="margin-bottom: 1.5rem;">
                    <h4 style="color: #333; margin-bottom: 1rem;">文献统计</h4>
                    <p><strong>文献总数:</strong> ${content.total_papers || 0} 篇</p>
                    <p><strong>平均质量评分:</strong> ${(content.average_quality || 0).toFixed(2)}/10</p>
                </div>
                
                ${content.key_papers && content.key_papers.length > 0 ? `
                    <div style="margin-bottom: 1.5rem;">
                        <h4 style="color: #333; margin-bottom: 1rem;">关键文献</h4>
                        ${content.key_papers.map((paper, index) => `
                            <div style="border-left: 3px solid #667eea; padding-left: 1rem; margin-bottom: 1rem;">
                                <p style="font-weight: bold; margin-bottom: 0.5rem;">${index + 1}. ${paper.title}</p>
                                <p style="color: #666; margin-bottom: 0.3rem;">
                                    作者: ${Array.isArray(paper.authors) ? paper.authors.join(', ') : paper.authors || '未知'}
                                </p>
                                <p style="color: #666; margin-bottom: 0.3rem;">
                                    期刊: ${paper.journal || '未知'} (${paper.year || '未知年份'})
                                </p>
                                <p style="color: #666;">
                                    质量评分: ${(paper.quality_score || 0).toFixed(1)}/10 | 
                                    相关性: ${(paper.relevance_score || 0).toFixed(1)}/10
                                </p>
                            </div>
                        `).join('')}
                    </div>
                ` : ''}
                
                ${content.research_gaps && content.research_gaps.length > 0 ? `
                    <div style="margin-bottom: 1.5rem;">
                        <h4 style="color: #333; margin-bottom: 1rem;">研究空白与机会</h4>
                        <ul style="padding-left: 2rem;">
                            ${content.research_gaps.map(gap => `<li style="margin-bottom: 0.5rem; line-height: 1.5;">${gap}</li>`).join('')}
                        </ul>
                    </div>
                ` : ''}
            `;
        }
        
        // 渲染实验设计章节
        function renderExperimentSection(content) {
            return `
                <div style="margin-bottom: 1.5rem;">
                    <h4 style="color: #333; margin-bottom: 1rem;">研究问题</h4>
                    <p style="background: #f8f9fa; padding: 1rem; border-radius: 8px; line-height: 1.6;">
                        ${content.research_question || '未定义研究问题'}
                    </p>
                </div>
                
                ${content.hypotheses && content.hypotheses.length > 0 ? `
                    <div style="margin-bottom: 1.5rem;">
                        <h4 style="color: #333; margin-bottom: 1rem;">研究假设</h4>
                        <ol style="padding-left: 2rem;">
                            ${content.hypotheses.map(hypothesis => `<li style="margin-bottom: 0.5rem; line-height: 1.5;">${hypothesis}</li>`).join('')}
                        </ol>
                    </div>
                ` : ''}
                
                ${content.experimental_groups && content.experimental_groups.length > 0 ? `
                    <div style="margin-bottom: 1.5rem;">
                        <h4 style="color: #333; margin-bottom: 1rem;">实验组设计</h4>
                        ${content.experimental_groups.map((group, index) => `
                            <div style="border: 1px solid #ddd; border-radius: 8px; padding: 1rem; margin-bottom: 1rem;">
                                <h5 style="color: #667eea; margin-bottom: 0.5rem;">${group.name || `实验组 ${index + 1}`}</h5>
                                <p style="color: #666; margin-bottom: 0.5rem;">${group.description || '无描述'}</p>
                                ${group.parameters && Object.keys(group.parameters).length > 0 ? `
                                    <div style="background: #f8f9fa; padding: 0.5rem; border-radius: 4px;">
                                        <strong>参数配置:</strong>
                                        ${Object.entries(group.parameters).map(([key, value]) => `<span style="margin-right: 1rem;">${key}: ${value}</span>`).join('')}
                                    </div>
                                ` : ''}
                            </div>
                        `).join('')}
                    </div>
                ` : ''}
                
                ${content.evaluation_metrics && content.evaluation_metrics.length > 0 ? `
                    <div style="margin-bottom: 1.5rem;">
                        <h4 style="color: #333; margin-bottom: 1rem;">评估指标</h4>
                        ${content.evaluation_metrics.map(metric => `
                            <div style="display: flex; justify-content: space-between; align-items: center; padding: 0.75rem; background: #f8f9fa; border-radius: 8px; margin-bottom: 0.5rem;">
                                <div>
                                    <strong>${metric.name || '未命名指标'}</strong>
                                    <p style="margin: 0; color: #666; font-size: 0.9rem;">${metric.description || '无描述'}</p>
                                </div>
                                ${metric.target ? `<span style="background: #667eea; color: white; padding: 4px 12px; border-radius: 20px; font-size: 0.8rem;">${metric.target}</span>` : ''}
                            </div>
                        `).join('')}
                    </div>
                ` : ''}
                
                ${content.methodology ? `
                    <div style="margin-bottom: 1.5rem;">
                        <h4 style="color: #333; margin-bottom: 1rem;">实验方法</h4>
                        <p style="line-height: 1.6; text-align: justify;">${content.methodology}</p>
                    </div>
                ` : ''}
            `;
        }
        
        // 渲染数据分析章节
        function renderAnalysisSection(content) {
            return `
                <div style="margin-bottom: 1.5rem;">
                    <h4 style="color: #333; margin-bottom: 1rem;">分析概览</h4>
                    <p><strong>分析类型:</strong> ${content.analysis_type || '未指定'}</p>
                </div>
                
                ${content.analysis_methods && content.analysis_methods.length > 0 ? `
                    <div style="margin-bottom: 1.5rem;">
                        <h4 style="color: #333; margin-bottom: 1rem;">分析方法</h4>
                        ${content.analysis_methods.map(method => `
                            <div style="border-left: 3px solid #28a745; padding-left: 1rem; margin-bottom: 1rem;">
                                <p style="font-weight: bold; margin-bottom: 0.5rem;">${method.name || '未命名方法'}</p>
                                <p style="color: #666;">${method.description || '无描述'}</p>
                            </div>
                        `).join('')}
                    </div>
                ` : ''}
                
                ${content.statistical_tests && content.statistical_tests.length > 0 ? `
                    <div style="margin-bottom: 1.5rem;">
                        <h4 style="color: #333; margin-bottom: 1rem;">统计检验</h4>
                        <ul style="padding-left: 2rem;">
                            ${content.statistical_tests.map(test => `<li style="margin-bottom: 0.5rem;">${test.name || test}</li>`).join('')}
                        </ul>
                    </div>
                ` : ''}
                
                ${content.expected_results ? `
                    <div style="margin-bottom: 1.5rem;">
                        <h4 style="color: #333; margin-bottom: 1rem;">预期结果</h4>
                        <p style="line-height: 1.6; text-align: justify;">${content.expected_results}</p>
                    </div>
                ` : ''}
            `;
        }
        
        // 渲染结论章节
        function renderConclusionSection(content) {
            return `
                ${content.summary ? `
                    <div style="margin-bottom: 1.5rem;">
                        <h4 style="color: #333; margin-bottom: 1rem;">项目总结</h4>
                        <p style="line-height: 1.6; text-align: justify;">${content.summary}</p>
                    </div>
                ` : ''}
                
                ${content.achievements && content.achievements.length > 0 ? `
                    <div style="margin-bottom: 1.5rem;">
                        <h4 style="color: #333; margin-bottom: 1rem;">主要成果</h4>
                        <ul style="padding-left: 2rem;">
                            ${content.achievements.map(achievement => `<li style="margin-bottom: 0.5rem; line-height: 1.5;">${achievement}</li>`).join('')}
                        </ul>
                    </div>
                ` : ''}
                
                ${content.future_work && content.future_work.length > 0 ? `
                    <div style="margin-bottom: 1.5rem;">
                        <h4 style="color: #333; margin-bottom: 1rem;">未来工作</h4>
                        <ul style="padding-left: 2rem;">
                            ${content.future_work.map(work => `<li style="margin-bottom: 0.5rem; line-height: 1.5;">${work}</li>`).join('')}
                        </ul>
                    </div>
                ` : ''}
                
                ${content.expected_impact ? `
                    <div style="margin-bottom: 1.5rem;">
                        <h4 style="color: #333; margin-bottom: 1rem;">预期影响</h4>
                        <p style="line-height: 1.6; text-align: justify;">${content.expected_impact}</p>
                    </div>
                ` : ''}
            `;
        }
        
        // 渲染通用章节
        function renderGenericSection(content) {
            let sectionHTML = '';
            
            if (typeof content === 'string') {
                sectionHTML += `<p style="margin-bottom: 1rem; line-height: 1.6;">${content}</p>`;
            } else if (content.summary) {
                sectionHTML += `<p style="margin-bottom: 1rem; line-height: 1.6;">${content.summary}</p>`;
            }
            
            // 渲染详细内容
            if (content.details) {
                if (Array.isArray(content.details)) {
                    sectionHTML += '<ul style="margin-bottom: 1rem; padding-left: 2rem;">';
                    content.details.forEach(detail => {
                        sectionHTML += `<li style="margin-bottom: 0.5rem; line-height: 1.5;">${detail}</li>`;
                    });
                    sectionHTML += '</ul>';
                } else if (typeof content.details === 'object') {
                    Object.entries(content.details).forEach(([key, value]) => {
                        sectionHTML += `<p style="margin-bottom: 0.5rem;"><strong>${key}:</strong> ${value}</p>`;
                    });
                }
            }
            
            return sectionHTML;
        }
        
        // 显示报告模态框
        function showReportModal(report, statistics) {
            try {
                // 创建模态框
                const modal = document.createElement('div');
                modal.style.cssText = `
                    position: fixed; top: 0; left: 0; width: 100%; height: 100%; 
                    background: rgba(0,0,0,0.8); z-index: 10000; display: flex; 
                    align-items: center; justify-content: center; overflow: auto;
                `;
                
                modal.innerHTML = `
                    <div style="background: white; width: 90%; max-width: 1000px; max-height: 90%; overflow: auto; border-radius: 8px; position: relative;">
                        <div style="position: sticky; top: 0; background: white; padding: 1rem; border-bottom: 1px solid #ddd; display: flex; justify-content: space-between; align-items: center; z-index: 1;">
                            <h3 style="margin: 0; color: #333;">📄 ${report.title}</h3>
                            <div>
                                <button onclick="downloadReport()" class="btn btn-success" style="margin-right: 0.5rem;">
                                    💾 下载PDF
                                </button>
                                <button onclick="printReport()" class="btn" style="margin-right: 0.5rem;">
                                    🖨️ 打印
                                </button>
                                <button onclick="this.closest('.report-modal').remove()" class="btn" style="background: #dc3545; color: white;">
                                    ✕ 关闭
                                </button>
                            </div>
                        </div>
                        <div style="padding: 2rem;">
                            ${window.currentReport.html}
                        </div>
                    </div>
                `;
                
                modal.className = 'report-modal';
                document.body.appendChild(modal);
                
                // 点击背景关闭模态框
                modal.addEventListener('click', function(e) {
                    if (e.target === modal) {
                        modal.remove();
                    }
                });
                
            } catch (error) {
                console.error('显示报告模态框错误:', error);
                showError('显示报告时出现错误');
            }
        }
        
        // 下载报告为PDF
        function downloadReport() {
            try {
                if (!window.currentReport) {
                    showError('没有可下载的报告');
                    return;
                }
                
                // 创建一个新窗口用于打印
                const printWindow = window.open('', '_blank');
                printWindow.document.write(`
                    <!DOCTYPE html>
                    <html>
                    <head>
                        <title>${window.currentReport.data.title}</title>
                        <style>
                            body { font-family: 'Times New Roman', serif; line-height: 1.6; margin: 0; padding: 20px; }
                            h1, h2, h3 { color: #333; }
                            .page-break { page-break-before: always; }
                            @media print {
                                body { margin: 0; }
                                .no-print { display: none; }
                            }
                        </style>
                    </head>
                    <body>
                        ${window.currentReport.html}
                    </body>
                    </html>
                `);
                printWindow.document.close();
                
                // 等待内容加载完成后触发打印
                setTimeout(() => {
                    printWindow.print();
                }, 500);
                
                showSuccess('报告已准备下载，请在打印对话框中选择"保存为PDF"');
                
            } catch (error) {
                console.error('下载报告错误:', error);
                showError('下载报告时出现错误');
            }
        }
        
        // 打印报告
        function printReport() {
            try {
                if (!window.currentReport) {
                    showError('没有可打印的报告');
                    return;
                }
                
                // 创建打印窗口
                const printWindow = window.open('', '_blank');
                printWindow.document.write(`
                    <!DOCTYPE html>
                    <html>
                    <head>
                        <title>${window.currentReport.data.title}</title>
                        <style>
                            body { font-family: 'Times New Roman', serif; line-height: 1.6; margin: 0; padding: 20px; }
                            h1, h2, h3 { color: #333; }
                            @media print {
                                body { margin: 0; }
                            }
                        </style>
                    </head>
                    <body>
                        ${window.currentReport.html}
                    </body>
                    </html>
                `);
                printWindow.document.close();
                
                setTimeout(() => {
                    printWindow.print();
                }, 500);
                
            } catch (error) {
                console.error('打印报告错误:', error);
                showError('打印报告时出现错误');
            }
        }

        // 调试函数：测试API连接
        async function debugTestAPI() {
            console.log('🧪 测试API连接...');
            
            try {
                // 测试项目详情API
                const projectResponse = await fetch(`/api/projects/${projectId}`);
                const projectApiData = await projectResponse.json();
                console.log('项目API响应:', projectApiData);
                
                // 测试文献搜索API
                const literatureResponse = await fetch('/api/literature/search', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ keywords: [], project_id: projectId })
                });
                const literatureData = await literatureResponse.json();
                console.log('文献API响应:', literatureData);
                
            } catch (error) {
                console.error('API测试失败:', error);
            }
        }
        
        // 下载报告
        function downloadReport(filename, content) {
            const blob = new Blob([content], { type: 'text/markdown;charset=utf-8' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            showSuccess('报告下载成功！');
        }
        
        // 加载项目成果交付物
        async function loadProjectDeliverables() {
            try {
                showInfo('正在加载项目成果数据...');
                
                const response = await fetch(`/api/projects/${projectId}/deliverables`);
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const data = await response.json();
                
                if (data.success) {
                    renderProjectDeliverables(data.deliverables);
                    showSuccess('项目成果数据加载成功！');
                } else {
                    showError(data.message || '加载项目成果失败');
                }
            } catch (error) {
                console.error('加载项目成果错误:', error);
                showError('加载项目成果时出现错误，请稍后重试');
            }
        }
        
        // 渲染项目成果交付物
        function renderProjectDeliverables(deliverables) {
            const content = document.getElementById('deliverablesContent');
            
            let html = `
                <div style="margin-bottom: 2rem;">
                    <h3 style="color: #333; margin-bottom: 1rem;">📊 项目统计概览</h3>
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; margin-bottom: 2rem;">
                        <div style="background: #e3f2fd; padding: 1rem; border-radius: 8px; text-align: center;">
                            <div style="font-size: 2rem; font-weight: bold; color: #1976d2;">${deliverables.statistics.total_tasks}</div>
                            <div style="color: #666;">总任务数</div>
                        </div>
                        <div style="background: #e8f5e8; padding: 1rem; border-radius: 8px; text-align: center;">
                            <div style="font-size: 2rem; font-weight: bold; color: #2e7d32;">${deliverables.statistics.completed_tasks}</div>
                            <div style="color: #666;">已完成任务</div>
                        </div>
                        <div style="background: #fff3e0; padding: 1rem; border-radius: 8px; text-align: center;">
                            <div style="font-size: 2rem; font-weight: bold; color: #f57c00;">${deliverables.statistics.success_rate}%</div>
                            <div style="color: #666;">成功率</div>
                        </div>
                        <div style="background: #fce4ec; padding: 1rem; border-radius: 8px; text-align: center;">
                            <div style="font-size: 2rem; font-weight: bold; color: #c2185b;">${deliverables.literature_summary.total_papers}</div>
                            <div style="color: #666;">文献数量</div>
                        </div>
                    </div>
                </div>
            `;
            
            // 研究计划成果
            if (deliverables.research_plan) {
                html += `
                    <div style="background: white; border: 1px solid #e0e0e0; border-radius: 8px; padding: 1.5rem; margin-bottom: 2rem;">
                        <h4 style="color: #667eea; margin-bottom: 1rem;">📋 研究计划成果</h4>
                        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 1rem;">
                            <div>
                                <strong>阶段数量:</strong> ${deliverables.research_plan.phases_count}
                            </div>
                            <div>
                                <strong>总时长:</strong> ${deliverables.research_plan.total_duration}
                            </div>
                            <div>
                                <strong>里程碑:</strong> ${deliverables.research_plan.milestones_count}
                            </div>
                            <div>
                                <strong>风险评估:</strong> ${deliverables.research_plan.risk_count} 项
                            </div>
                        </div>
                        <div style="margin-top: 1rem; padding: 0.5rem; background: #f8f9fa; border-radius: 4px;">
                            <strong>状态:</strong> ${deliverables.research_plan.status} | 
                            <strong>创建时间:</strong> ${new Date(deliverables.research_plan.created_at).toLocaleString()}
                        </div>
                    </div>
                `;
            }
            
            // 实验设计成果
            if (deliverables.experiment_design) {
                html += `
                    <div style="background: white; border: 1px solid #e0e0e0; border-radius: 8px; padding: 1.5rem; margin-bottom: 2rem;">
                        <h4 style="color: #667eea; margin-bottom: 1rem;">🧪 实验设计成果</h4>
                        <div style="margin-bottom: 1rem;">
                            <strong>研究问题:</strong> ${deliverables.experiment_design.research_question}
                        </div>
                        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 1rem;">
                            <div>
                                <strong>假设数量:</strong> ${deliverables.experiment_design.hypotheses_count}
                            </div>
                            <div>
                                <strong>实验组:</strong> ${deliverables.experiment_design.experimental_groups_count}
                            </div>
                            <div>
                                <strong>评估指标:</strong> ${deliverables.experiment_design.evaluation_metrics_count}
                            </div>
                        </div>
                        <div style="margin-top: 1rem; padding: 0.5rem; background: #f8f9fa; border-radius: 4px;">
                            <strong>状态:</strong> ${deliverables.experiment_design.status} | 
                            <strong>创建时间:</strong> ${new Date(deliverables.experiment_design.created_at).toLocaleString()}
                        </div>
                    </div>
                `;
            }
            
            // 数据分析成果
            if (deliverables.analysis_config) {
                html += `
                    <div style="background: white; border: 1px solid #e0e0e0; border-radius: 8px; padding: 1.5rem; margin-bottom: 2rem;">
                        <h4 style="color: #667eea; margin-bottom: 1rem;">📊 数据分析成果</h4>
                        <div style="margin-bottom: 1rem;">
                            <strong>分析类型:</strong> ${deliverables.analysis_config.analysis_type}
                        </div>
                        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 1rem;">
                            <div>
                                <strong>数据源:</strong> ${deliverables.analysis_config.data_sources_count}
                            </div>
                            <div>
                                <strong>分析方法:</strong> ${deliverables.analysis_config.analysis_methods_count}
                            </div>
                            <div>
                                <strong>统计检验:</strong> ${deliverables.analysis_config.statistical_tests_count}
                            </div>
                            <div>
                                <strong>可视化类型:</strong> ${deliverables.analysis_config.visualization_types_count}
                            </div>
                        </div>
                        <div style="margin-top: 1rem; padding: 0.5rem; background: #f8f9fa; border-radius: 4px;">
                            <strong>状态:</strong> ${deliverables.analysis_config.status} | 
                            <strong>创建时间:</strong> ${new Date(deliverables.analysis_config.created_at).toLocaleString()}
                        </div>
                    </div>
                `;
            }
            
            // 文献研究成果
            html += `
                <div style="background: white; border: 1px solid #e0e0e0; border-radius: 8px; padding: 1.5rem; margin-bottom: 2rem;">
                    <h4 style="color: #667eea; margin-bottom: 1rem;">📚 文献研究成果</h4>
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 1rem;">
                        <div>
                            <strong>文献总数:</strong> ${deliverables.literature_summary.total_papers}
                        </div>
                        <div>
                            <strong>平均质量:</strong> ${deliverables.literature_summary.average_quality}/10
                        </div>
                        <div>
                            <strong>平均相关性:</strong> ${deliverables.literature_summary.average_relevance}/10
                        </div>
                        <div>
                            <strong>高质量文献:</strong> ${deliverables.literature_summary.high_quality_papers}
                        </div>
                    </div>
                </div>
            `;
            
            // 任务执行历史
            if (deliverables.task_history && deliverables.task_history.length > 0) {
                html += `
                    <div style="background: white; border: 1px solid #e0e0e0; border-radius: 8px; padding: 1.5rem; margin-bottom: 2rem;">
                        <h4 style="color: #667eea; margin-bottom: 1rem;">📋 任务执行历史</h4>
                        <div style="max-height: 300px; overflow-y: auto;">
                `;
                
                deliverables.task_history.forEach(task => {
                    const statusColor = task.status === 'completed' ? '#28a745' : 
                                       task.status === 'running' ? '#ffc107' : '#dc3545';
                    html += `
                        <div style="border-bottom: 1px solid #eee; padding: 0.75rem 0; display: flex; justify-content: space-between; align-items: center;">
                            <div>
                                <strong>${task.name}</strong>
                                <div style="font-size: 0.9rem; color: #666;">
                                    类型: ${task.type} | 
                                    ${task.duration ? `耗时: ${task.duration}` : ''}
                                </div>
                            </div>
                            <div style="color: ${statusColor}; font-weight: bold;">
                                ${task.status === 'completed' ? '✅ 已完成' : 
                                  task.status === 'running' ? '🔄 执行中' : '❌ 失败'}
                            </div>
                        </div>
                    `;
                });
                
                html += `
                        </div>
                    </div>
                `;
            }
            
            content.innerHTML = html;
        }
        
        // 导出成果报告
        async function exportDeliverables() {
            try {
                showInfo('正在导出成果报告...');
                
                const response = await fetch(`/api/projects/${projectId}/deliverables`);
                const data = await response.json();
                
                if (data.success) {
                    const deliverables = data.deliverables;
                    
                    // 生成成果报告内容
                    let reportContent = `# ${deliverables.project_info.title} - 项目成果报告\n\n`;
                    reportContent += `**生成时间:** ${new Date().toLocaleString()}\n`;
                    reportContent += `**项目ID:** ${deliverables.project_info.id}\n\n`;
                    
                    reportContent += `## 项目概览\n`;
                    reportContent += `- **研究领域:** ${deliverables.project_info.research_area}\n`;
                    reportContent += `- **研究方法:** ${deliverables.project_info.methodology}\n`;
                    reportContent += `- **项目状态:** ${deliverables.project_info.status}\n`;
                    reportContent += `- **完成进度:** ${deliverables.project_info.progress}%\n\n`;
                    
                    reportContent += `## 成果统计\n`;
                    reportContent += `- **总任务数:** ${deliverables.statistics.total_tasks}\n`;
                    reportContent += `- **已完成任务:** ${deliverables.statistics.completed_tasks}\n`;
                    reportContent += `- **成功率:** ${deliverables.statistics.success_rate}%\n`;
                    reportContent += `- **文献数量:** ${deliverables.literature_summary.total_papers}\n\n`;
                    
                    if (deliverables.research_plan) {
                        reportContent += `## 研究计划成果\n`;
                        reportContent += `- **阶段数量:** ${deliverables.research_plan.phases_count}\n`;
                        reportContent += `- **总时长:** ${deliverables.research_plan.total_duration}\n`;
                        reportContent += `- **里程碑数量:** ${deliverables.research_plan.milestones_count}\n\n`;
                    }
                    
                    if (deliverables.experiment_design) {
                        reportContent += `## 实验设计成果\n`;
                        reportContent += `- **研究问题:** ${deliverables.experiment_design.research_question}\n`;
                        reportContent += `- **假设数量:** ${deliverables.experiment_design.hypotheses_count}\n`;
                        reportContent += `- **实验组数量:** ${deliverables.experiment_design.experimental_groups_count}\n\n`;
                    }
                    
                    // 下载报告
                    const blob = new Blob([reportContent], { type: 'text/markdown;charset=utf-8' });
                    const url = URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = `${deliverables.project_info.title}_成果报告_${new Date().toISOString().slice(0, 10)}.md`;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    URL.revokeObjectURL(url);
                    
                    showSuccess('成果报告导出成功！');
                } else {
                    showError('导出成果报告失败');
                }
            } catch (error) {
                console.error('导出成果报告错误:', error);
                showError('导出成果报告时出现错误，请稍后重试');
            }
        }
        
        // 真实文献搜索
        async function searchRealLiterature() {
            try {
                showInfo('正在执行真实文献搜索，请稍候...');
                
                const response = await fetch('/api/literature/real-search', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        project_id: projectId,
                        keywords: [] // 让后端从项目信息中提取关键词
                    })
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const data = await response.json();
                
                if (data.success) {
                    showSuccess(`真实文献搜索完成！找到 ${data.total_results} 篇相关文献`);
                    renderLiteratureResults(data);
                    switchToTab('literature');
                    
                    // 重新加载项目数据以更新统计信息
                    loadLiteratureData();
                } else {
                    showError(data.message || '真实文献搜索失败');
                }
            } catch (error) {
                console.error('真实文献搜索错误:', error);
                showError('真实文献搜索时出现错误，请稍后重试');
            }
        }
        
        // 在控制台中提供调试命令
        console.log('🛠️ 调试命令已加载:');
        console.log('  debugProjectData() - 查看项目数据');
        console.log('  debugReloadData() - 重新加载数据');
        console.log('  debugTestAPI() - 测试API连接');
    
    </script>
</body>
</html>